1. 程式人生 > >[leetcode]387. First Unique Character in a String

[leetcode]387. First Unique Character in a String

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.

分析:

返回第一個非重複元素的下標,不存在則返回-1。建立雜湊表,記錄每個字元的個數,再從雜湊表開始處遍歷,如果某個字元的個數為1,返回索引即可。

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