non repeating character code example
Example 1: non repeating char
def first_non_repeating_character(str1):
char_order = []
ctr = {}
for c in str1:
if c in ctr:
ctr[c] += 1
else:
ctr[c] = 1
char_order.append(c)
for c in char_order:
if ctr[c] == 1:
return c
return None
print(first_non_repeating_character('abcdef'))
print(first_non_repeating_character('abcabcdef'))
print(first_non_repeating_character('aabbcc'))
Example 2: first unique character in a string python
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
frequency = {}
for i in s:
if i not in frequency:
frequency[i] = 1
else:
frequency[i] +=1
for i in range(len(s)):
if frequency[s[i]] == 1:
return i
return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))