剑指offer34_第一个只出现一次的字符_题解
第一个只出现一次的字符
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
示例1
输入
"google"返回值
4
分析
方案一:哈希
字符统计:遍历字符串s中的每个字符c
查找数量为1的字符:遍历字符串s中的每个字符c
代码
/**
1.时间复杂度:O(n)
n为字符串s的长度
2.空间复杂度:O(1)
题目指出s只包含小写字母,最多有26个不同字符
**/
class Solution
{
public:
    int FirstNotRepeatingChar(string str)
    {
        map<char, bool> dic;
        for (const char ch : str)
        {
            dic[ch] = (dic.find(ch) == dic.end());
        }
        for (int i = 0; i < str.length(); ++i)
        {
            if (dic[str[i]])
            {
                return i;
            }
        }
        return -1;
    }
};
方案二:有序哈希
相比于方法一,方法二减少了第二轮遍历的循环次数,当重复字符很多时,方法二效率更高
代码
/**
1.时间复杂度:O(n)
2.空间复杂度:O(1)
**/
class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        map<char, bool> dic;
        vector<int> vec;
        for(int i = 0; i < str.length(); i++){
            if(dic.find(str[i]) == dic.end())
                vec.emplace_back(i);
            dic[str[i]] = dic.find(str[i]) == dic.end();
        }
        for(const int k : vec){
            if(dic[str[k]]){
                return k;
            }
        }
        return -1;
    }
};

                
            
        
浙公网安备 33010602011771号