mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
691 B
691 B
387. First Unique Character in a String
思路
先遍历一遍字符串,记录每个字符出现的次数,再遍历一遍找出第一个没有重复的字符。
由于题目说了全部字符都是小写字母,所以开辟一个大小为26的数组记录字符出现次数即可。
时间复杂度O(n)
C++
class Solution {
public:
int firstUniqChar(string s) {
vector<int>count(26, 0);
for(int i = 0; i < s.size(); i++) count[s[i] - 'a']++;
for(int i = 0; i < s.size(); i++)
if(count[s[i] - 'a'] == 1) return i;
return -1;
}
};