跳到主要内容

387 字符串中的第一个唯一字符

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnx13t/

https://leetcode.cn/problems/reverse-integer/description/

cost: 6m48s

class Solution {
public:
int firstUniqChar(string s) {
unordered_map<int, int> m;
for (int i = 0; i < s.size(); i++) {
char ch = s[i];
if (m.count(ch)) {
m[ch] = -1;
} else {
m[ch] = i;
}
}
int r = -1;
for (const auto [_, pos] : m) {
if (pos != -1) {
if (r == -1 || r > pos) {
r = pos;
}
}
}
return r;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(∣Σ∣),其中 Σ 是字符集