LeetCode——387. 字串中的第一個唯一字元
阿新 • • 發佈:2020-12-25
技術標籤:C++leetcode雜湊字串leetcode資料結構
題目描述:
給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。
提示:你可以假定該字串只包含小寫字母。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
程式碼如下:
class Solution {
public:
int firstUniqChar(string s) {
int size=s.size();
unordered_map<char,int>m;
int ans= -1;
for(int i=0;i<size;i++){
m[s[i]]++;
}
for(int j=0;j<size;++j){
if(m[s[j]]==1){
ans=j;
break;
}
}
return ans;
}
};
執行結果: