Day3字符个数统计

215 阅读2分钟

Day3

描述

编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ,包括 0 和 127 ),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次

例如,对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3 。

数据范围: 1 \le n \le 500 \1≤n≤500

输入描述:

输入一行没有空格的字符串。

输出描述:

输出 输入字符串 中范围在(0~127,包括0和127)字符的种数。

示例1

输入:

abc

复制

输出:

3

复制

示例2

输入:

aaa

复制

输出:

1

思路

  • 法1:直接用C++ 无序容器set,利用容器不重复,且无序的特点,直接将字符串输入到容器里面,然后遍历容器,容器里面存在的字符数就是答案
  • 法2:用map容器进行键值映射,然后直接遍历容器,统计容器内字符数便可
  • 法3:手动模拟hash映射,出现一次直接赋值为1,字符数+1,最后输出字符数便可

复杂度

  • 法1:Time:O(n),Spaec:O(n)
  • 法2:Time:O(n),Spaec:O(n)
  • 法3:Time:O(n),Spaec:O(n)

具体实现

#include <math.h>
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <cstring>//#include "./include/list/sqlist.h"
​
using namespace std;
​
const int maxn = 550;
//day3
//编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ,包括 0 和 127 ),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次
//例如,对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3 。
//法1:STL set容器法
//解题思路:设置无序set容器,然后直接读入字符串,直接遍历set容器里面的数,便是答案
/**
 * @description: 时间复杂度O(n),空间复杂度O(n)
 * @param {string} s
 * @return {*}
 */
int CountDifferentCharacter(string s){
    int len_s = s.length();
    if(s.empty()) return 0;
    int ans = 0;
    //先设置计数数组
    //unordered_map<char,int> hash;//哈希表法,直接记录对应数组出现的次数
    unordered_set<char> hash;//无序set容器,里面的值是不重复的
    //将字符串每个输入到set数组中
    for(int i = 0; i < len_s; i++){
        hash.insert(s[i]);
    }
    //遍历set中数据
    while(!hash.empty()){
        char c = (*hash.begin());//取出迭代器的元素
        ans++;
        hash.erase(c);//删除迭代器元素
    }
    return ans;
}
​
​
//法2:用map进行键值映射
/**
 * @description: O(n)+O(n)
 * @param {string} s
 * @return {*}
 */
int CountDifferentCharacterII(string s){
    int len_s = s.length();//字符串长度
    if(s.empty()) return 0;
    int ans = 0;
    unordered_map<char,int> hash;
    //将字符串输入到map数组中
    for(int i = 0; i < len_s; i++){
        if(!hash.count(s[i])) hash[s[i]] = 1;//记录出现的次数
    }
    for(auto iter = hash.begin(); iter != hash.end(); iter++){
        ans++;
    }
    return ans;
}
​
​
//法3:手动模拟map,hash表思想
/**
 * @description: O(n)+O(n)
 * @param {string} s
 * @return {*}
 */
int CountDifferentCharacterIII(string s){
    int len_s = s.length();
    if(s.empty()) return 0;
    int ans = 0;
    char c[127] = {0};//用来进行键值映射的数组
    for(int i = 0 ;i < len_s; i++){
        if(c[s[i]] == 0){
            c[s[i]] = 1;
            ans++;
        }
    }
    return ans;
}
​
int main(){
     string s;
    //用到getline
    getline(cin,s);//将输入流直接赋给s字符串
    //char c;
    //cin >> c;
    int lastans = CountDifferentCharacter(s);
    printf("%d",lastans);
    
    system("pause");
    return 0;
}
​

image.png

小结

  1. 懂得利用STL容器Set进行解决问题,类似的STL无序容器库还有map,mutlmap,mutlset,set这几种容器,要对比其区别(c.biancheng.net/view/7231.h…)