First unique character in a string
August 16, 2022
array-and-hashmapProblem URL: First unique character in a string
First we will count each character of the string. Then we iterate from the beginning, check which character has character count 1, return that. If we can't find anything with character count 1, we return -1.
class Solution:
def firstUniqChar(self, s: str) -> int:
count = collections.Counter(list(s))
for i, c in enumerate(s):
if count[c] == 1:
return i
return -1
Time Complexity: O(n)
Space Complexity: O(n)