- First Unique Character in a String
LC 387
Find the first unique character in a given string. You can assume that there is at least one unique character in the string.
Example
For "abaccdeff", return 'b'.
class Solution:
"""
@param str: str: the given string
@return: char: the first unique character in a given string
"""
def firstUniqChar(self, str):
counter = {}
for i in range(len(str)):
counter[str[i]] = counter.get(str[i], 0) + 1
for i in range(len(str)):
if counter[str[i]] == 1:
return str[i]
return None
- Time:
O(n)
- Space:
O(n)
Note:
- I tried to write:
if str[i] not in counter:
counter[str[i]] = 1
else:
counter[str[i]] += 1
but it is better to utilize python3. Use counter.get(key, default)
- use
counter
to better describe the usage of dictionary.
网友评论