0%

剑指 Offer 50. 第一个只出现一次的字符

剑指 Offer 50. 第一个只出现一次的字符

遍历两次
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
char firstUniqChar(string s) {
int memo[26]{ 0 };
for(auto& ch : s)
memo[ch - 'a'] += 1;
for(auto& ch : s)
if(memo[ch - 'a'] == 1)
return ch;
return ' ';
}
};
用vector记录插入的数据,在有大量重复的情况下会笔第一种快
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
char firstUniqChar(string s) {
int memo[26]{ 0 };
vector<char> v;
for(auto& ch : s)
{
if(!memo[ch - 'a'])
v.push_back(ch);
memo[ch - 'a'] += 1;
}
for(auto& ch : v)
if(memo[ch - 'a'] == 1)
return ch;
return ' ';
}
};