LeetCode 387 字符串中的第一个唯一字符 HERODING的LeetCode之路

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

示例:

s = “leetcode”
返回 0

s = “loveleetcode”
返回 2

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
首先一定是要统计字符的数目,否则无法判断是否唯一,再重头遍历一遍字符串,如果当前字符的数目为1,直接返回下标,代码如下:

class Solution {
    
    
public:
    int firstUniqChar(string s) {
    
    
        unordered_map<char, int> mp;
        for(auto l : s){
    
    
            mp[l] ++;
        }
        for(int i = 0 ; i < s.length(); i ++){
    
    
            if(mp[s[i]] == 1){
    
    
                return i;
            }
        }
        return -1;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/zui-jian-dan-de-si-lu-by-heroding-pclq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/111570465