方法一:建立两个辅助列表,遍历字符串
class Solution:
def firstUniqChar(self, s: str) -> str:
uniq_list = []
repeat_list = []
for char in s:
if char not in uniq_list and char not in repeat_list:
uniq_list.append(char)
elif char in repeat_list:
continue
else:
uniq_list.remove(char)
repeat_list.append(char)
if not uniq_list:
return ' '
return uniq_list[0]
方法二:使用字典计数
class Solution:
def firstUniqChar(self, s: str) -> str:
freq_dict = {}
for char in s:
if char not in freq_dict:
freq_dict[char] = 1
else:
freq_dict[char] += 1
if not freq_dict:
return ' '
for key, value in freq_dict.items():
if value == 1:
return key
return ' '
方法三:使用字典保存字符出现的索引
class Solution:
def firstUniqChar(self, s: str) -> str:
index_dict = {} # 保存字符出现的索引,若重复,则设为-1
for i, char in enumerate(s):
if char in index_dict:
index_dict[char] = -1
else:
index_dict[char] = i
first = len(s)
for key, value in index_dict.items():
if value != -1:
return key
return ' '