from collections import OrderedDict
def find_first_unique_char(s):
count = OrderedDict()
for char in s:
if char in count:
count[char] += 1
else:
count[char] = 1
for char in s:
if count[char] == 1:
return char
return None
print(find_first_unique_char('abcacd')) # 输出:'b'
2.Python3.7+字典已经是有序的了
def find_first_unique_char(s):
count = {}
for char in s:
if char in count:
count[char] += 1
else:
count[char] = 1
for char in s:
if count[char] == 1:
return char
return None
print(find_first_unique_char('abcacd')) # 输出:'b'
3.切片方式
def find_first_unique_char(s: str) -> str:
for i in range(len(s)):
if s[i] not in s[:i] and s[i] not in s[i+1:]:
return s[i]
return None
# 测试
s = "abcacd"
print(find_first_unique_char(s)) # 输出:b