https://leetcode.com/problems/first-unique-character-in-a-string/description/
Solution 1. Use int array as hash table.
int firstUniqChar(string s) {
int m[26+'a'] = {0};
for(auto c : s){
m[c]++;
}
for(int i=0; i<s.size();i++){
if(m[s[i]]==1) return i;
}
return -1;
}
Solution 2. Use hash table.
int firstUniqChar(string s) {
unordered_map<char,int> m;
for(int i=0;i<s.size();i++){
m[s[i]]++;
}
for(int i=0;i<s.size();i++){
if(m[s[i]]==1) return i;
}
return -1;
}
No comments:
Post a Comment