Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode" return 2.
Note: You may assume the string contains only lowercase English letters.
Source
from collections import Counter
def first_unique_char(s):
"""
Time Complexity: O(n)
Space Complexity: O(n)
"""
frequency = Counter(s)
for index, char in enumerate(s):
if frequency[char] == 1:
return index
return -1
s = "leetcode"
first_unique_char(s)
0
s = "loveleetcode"
first_unique_char(s)
2