algorithm notes: leetcode#387 first unique character in a string

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
class :
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
counter = {}
for c in s:
counter[c] = counter.get(c, 0)+1
for i, c in enumerate(s):
if counter[c] == 1:
return i
return -1

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class {
public int firstUniqChar(String s) {
Map<Character, Integer> counter = new HashMap<>();
for(char c : s.toCharArray()){
counter.put(c, counter.getOrDefault(c, 0)+1);
}
for(int i = 0; i < s.length(); i++){
if(counter.get(s.charAt(i))==1){
return i;
}
}
return -1;
}
}

Time complexity

O(n).

Space complexity

O(n).


387. First Unique Character in a String
(中文版) 算法笔记: 力扣#387 字符串中的第一个唯一字符