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:
1 2
| Input: s = "leetcode" Output: 0
|
Example 2:
1 2
| Input: s = "loveleetcode" Output: 2
|
Example 3:
1 2
| Input: s = "aabb" Output: -1
|
哈希表存储频数:
时间复杂度:O(n)
空间复杂度:O(S),S为字符集大小,本题中S不大于26。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int firstUniqChar(string s) { unordered_map<int, int> frequency; for (char ch: s) { ++frequency[ch]; } for (int i = 0; i < s.size(); ++i) { if (frequency[s[i]] == 1) { return i; } } return -1; } };
|
哈希表存储索引:
时间复杂度:O(n)
空间复杂度:O(S),S为字符集大小,本题中S不大于26。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: int firstUniqChar(string s) { unordered_map<int, int> position; int n = s.size(); for (int i = 0; i < n; ++i) { if (position.count(s[i])) { position[s[i]] = -1; } else { position[s[i]] = i; } } int first = n; for (auto [_, pos]: position) { if (pos != -1 && pos < first) { first = pos; } } if (first == n) { first = -1; } return first; } };
|
队列:
时间复杂度:O(n)
空间复杂度:O(S),S为字符集大小,本题中S不大于26。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int firstUniqChar(string s) { unordered_map<char, int> position; queue<pair<char, int>> q; int n = s.size(); for (int i = 0; i < n; ++i) { if (!position.count(s[i])) { position[s[i]] = i; q.emplace(s[i], i); } else { position[s[i]] = -1; while (!q.empty() && position[q.front().first] == -1) { q.pop(); } } } return q.empty() ? -1 : q.front().second; } };
|