面试题35:第一个只出现一次的字符

题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

题目分析
用哈希表存储字符串中每个字符出现的次数。第一次遍历获取每个字符的出现次数,第二次遍历找到一个出现一次的字符并返回它的位置,时间复杂度o(n)。

代码:
stl中map默认是按照key从小到大排序

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        map<char, int> letter_count;
        if (str.size() == 0)
            return -1;
        int pos = 0;
        for (int i = 0; i < str.size(); i ++)
            letter_count[str[i]] ++;
        auto map_it = letter_count.begin();
        for (; map_it != letter_count.end(); map_it ++)
            if (map_it->second == 1)
                break;
        for (;pos < str.size(); pos ++)
            if (letter_count[str[pos]] == 1)
                break;
        return pos;
    }
};
class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        map<char, int> letter_count;
        if (str.size() == 0)
            return -1;
        int pos = 0;
        const int tableSize = 256;
        int hashTable[tableSize];
        for (int i = 0; i < tableSize; i ++)
            hashTable[i] = 0;
        for (int j = 0; j < str.size(); j ++)
            hashTable[str[j]] ++;
        for (; pos < str.size(); pos ++)
            if (hashTable[str[pos]] == 1)
                break;

        return pos;
    }
};

猜你喜欢

转载自blog.csdn.net/zxc995293774/article/details/80300992