387. First Unique Character in a String

  • 46.1%

https://leetcode.com/problems/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.

1
2
3
4
5
6
7
8
> Examples:
>
> s = "leetcode"
> return 0.
>
> s = "loveleetcode",
> return 2.
>

Note: You may assume the string contain only lowercase letters.

java

29ms, August 28th, 2016

https://discuss.leetcode.com/topic/55148/java-7-lines-solution-29ms

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public int firstUniqChar(String s) {
int freq[] = new int[26];
for(int i = 0; i < s.length(); i++)
freq[s.charAt(i) - 'a']++;
for(int i = 0; i < s.length(); i++)
if(freq[s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
}

cpp

55ms, August 28th, 2016

https://discuss.leetcode.com/topic/55132/c-56ms-5-lines

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int firstUniqChar(string s) {
int alphabet[26] = {0};
for (int i = 0; i < s.size(); ++i){++alphabet[s[i] -'a'];}
int i = 0;
while (i < s.size() && alphabet[s[i]-'a'] > 1) ++i;
return i == s.size() ? -1 : i;
}
};

python

solution 1:

240ms, August 28th, 2016

https://discuss.leetcode.com/topic/55099/python-very-easy-solution

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for x in s:
if s.find(x) == s.rfind(x):
return s.find(x)
return -1
谢谢你,可爱的朋友。