題目描述
給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事項:您可以假定該字符串只包含小寫字母。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
結果
解題思路是用哈希數組
class Solution {
public:
int firstUniqChar(string s) {
int hash[26] = { 0 };
for(char c : s)
hash[c - 'a']++;
for(int i = 0; i < s.size(); i++)
if(1 == hash[s[i] - 'a'])
return i;
return -1;
}
};