更新时间:2022-10-03 13:53:02
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
此题比较简单
代码如下:
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
26
27
28
29
30
31
32
|
class Solution {
public :
int firstUniqChar(string s) {
set< char > myset;
if (s.empty())
{
return -1;
}
for ( int i = 0 ; i < s.size();i++)
{
char c = s[i];
int j;
if (myset.find(c) != myset.end())
{
continue ;
}
for (j = i + 1; j < s.size();j++)
{
if (s[j] == s[i])
{
myset.insert(c);
break ;
}
}
if (j == s.size() )
{
return i;
}
}
return -1;
}
}; |