LeetCode 387. First Unique Character in a String
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode"
Output: 0
Example 2:
Input: s = "loveleetcode"
Output: 2
method
哈希表存储每个字符的出现次数,返回第一个出现次数为1的字符下标
int firstUniqChar(string s) {
int hash[26] = {0};
for (int i = 0; i < s.size(); i++) {
hash[s[i] - 'a']++;
}
for (int i = 0; i < s.size(); i++) {
if (hash[s[i] - 'a'] == 1) return i;
}
return -1;
}