35 - 找出字符串中第一个只出现一次的字符

来源:互联网 发布:sql server 收费 编辑:程序博客网 时间:2024/04/29 08:45

在一个字符串中找到第一个只出现一次的字符。
如输入”abaccdeff”,输出’b’


解析:
使用一个数组,记录每个字符出现的次数,最后遍历计数数组,第一个个数为 1 的即为结果。
由于字符char,只有8 bit, 只有255种可能,因此只需声明一个255大小的数组。

遍历一次字符串,遍历2次计数数组:时间复杂度O(n)
空间占用255*int = 512 Byte,是一个固定大小:空间复杂度O(1)

当需要统计某个或某些字符是否出现或出现在字符串中的次数时,可以通过数组实现一个简易的hash表
用很小的空间换来时间效率的提升。

#include <iostream>using namespace std;char FirstNotRepeatChar(string s) {    int size = s.size();    if (size == 0)        return '\0';    const int M = 255; // 表大小,char :1 Byte,0~255    unsigned int* count = new unsigned int [M];    for (int i = 0; i < M; i++)        count[i] = 0;    for (int j = 0; j < size; j++)        count[s[j]-'\0']++;    char result;    for (int i = 0; i < size; i++) {        if (count[s[i]-'\0'] == 1) {            result = s[i];            break;        }    }    delete []count;    return result;}int main() {    string s = "testonline";    cout << FirstNotRepeatChar(s) << endl;}
0 0