【leetcode】(初级算法-字符串)字符串中的第一个唯一字符【Python】
字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
注意事项:
您可以假定该字符串只包含小写字母。
方法一:判断第i个字符是否在除i之外的字符串中
# 字符串的第一个唯一字符
# S = 'leetcode'
S = 'loveleetcode'
# S = 'cc'
# 方法一:判断第i个字符是否在除i之外的字符串中
def firstUniqChar(s):
a = -1
for i in range(len(s)):
if (s[i] not in s[i+1:]) and (s[i] not in s[:i]):
a = i
break
return a
print(firstUniqChar(S))
方法二:使用字典记录字符出现的次数
# 方法二:使用字典记录字符出现的次数
def firstUniqChar(s):
dic = {}
for char in s:
if char in dic:
dic[char] += 1
else:
dic[char] = 1
for i in range(len(s)):
if dic[s[i]] == 1:
return i
return -1
# 程序运行到所遇到的第一个return即返回(退出def块)
# 不会再运行第二个return
print(firstUniqChar(S))