0%

387. First Unique Character in a String

hashmap O(n)
这个方法比简单统计字母频要快

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int firstUniqChar(string s) {
int f[26] = {0};
for (const auto &c : s) {
++f[c - 'a'];
}
int n = s.length();
for (int i = 0; i < n; ++i) {
if (f[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
};

把重复的字母的下标全部记成n,不重复的则记成i,然后遍历找出最小的i

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int firstUniqChar(string s) {
vector<int> m(26, INT_MAX);
int n = s.length();
for (int i = 0; i < n; ++i) {
int k = s[i] - 'a';
if (m[k] == INT_MAX) {
m[k] = i;
} else if (m[k] < n) {
m[k] = n;
}
}
int res = *min_element(m.begin(), m.end());
return res < n ? res : -1;
}
};