題目: LeetCode - 387. First Unique Character in a String

題目說明

給一個字串,求字串中只出現過一次的字元的 index

解題思路

使用一個陣列儲存字元出現的次數即可。由於測資只包含小寫的英文字母,所以陣列大小設為 26。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int firstUniqChar(string s) {
int count[26] = {}, n = s.size();
for(auto i : s)
++count[i - 'a'];
for(int i = 0; i < n; ++i)
if(count[s[i] - 'a'] == 1)
return i;
return -1;
}
};