【leetcode】字符串中的第一个唯一字符c++

题目描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = “leetcode”
返回 0
s = “loveleetcode”
返回 2

提示:你可以假定该字符串只包含小写字母。

代码:

class Solution {
    
    
public:
    int firstUniqChar(string s) {
    
    
        long long n=s.length();
        unordered_map<char,int> m;
        for(long long i=0;i<n;i++){
    
    
            if(m.find(s[i]) == m.end()){
    
    
                m.insert(pair<char,int>(s[i],1));
            }
            else {
    
    
                m[s[i]] = m[s[i]] + 1;
            }
        }
        char x = '*';
        unordered_map<char, int>::iterator iter;  
        for(iter = m.begin(); iter != m.end(); iter++){
    
    
            cout<<iter->first<<" "<<iter->second<<endl;
        }
        for(iter = m.begin(); iter != m.end(); iter++){
    
    
            if(iter->second == 1){
    
    
                x = iter->first;
            }
        }
        if(x == '*')return -1;
        for(long long i=0;i<n;i++){
    
    
            if(s[i]==x)return i;
        }
        return -1;
    }
};

在这里插入图片描述

注意:
用unordered_map代替map,因为map是有序的,会自动按照key值排序,此题需要求string中第一个满足条件的元素,不能打乱string中元素的顺序,∴使用无序哈希unordered_map。

猜你喜欢

转载自blog.csdn.net/qq_40315080/article/details/120625952