LeetCode: 387. First Unique Character in a String

051105

题目

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

我的解题思路

这道题的解题思路跟LeetCode:383. Ransom Note类似,首先可以先建立一个map,遍历字符串,计算每个字符的出现的次数,之后返回第一个只出现一次的字符的位置即可。

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

围观了一波大佬的解法,发现能跟上了,加油!

猜你喜欢

转载自blog.csdn.net/liveway6/article/details/90108486
今日推荐