LeetCode/solutions/387. First Unique Character in a String.md
2019-09-13 23:08:41 +08:00

19 lines
694 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/)
# 思路
先遍历一遍字符串,记录每个字符出现的次数,再遍历一遍找出第一个没有重复的字符。
由于题目说了全部字符都是小写字母所以开辟一个大小为26的数组记录字符出现次数即可。
时间复杂度O(n)
# C++
```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;
}
};
```