给定一个字符串,找到字符串中第一个不重复的字符,并返回它的下标。如果不存在不重复的字符,则返回-1
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
注意:
你可以假设字符串中只存在小写字母
1:用set()方法,将字符串s转为不包含重复字母的随机排列集合sStr。访问sStr,生成字典chaDic,字典中存放字母和其在字符串s中出现的次数(cha:num)。访问字符串s中元素,在chaDic中查询该元素对应的次数,如果次数为1就输出该元素在字符串s中对应的下标
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
sSet = set(s)
chaDic = {}
for i in sSet:
chaDic[i] = s.count(i)
for i, j in enumerate(s):
if chaDic.get(j) == 1:
return i
return -1
另一种更灵活的写法
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
chaDic = {}
for i, j in enumerate(s):
if not chaDic.get(j):
count = s[i:].count(j)
if count == 1:
return i
else:
chaDic[j] = count
return -1
2:字符串s只包含小写字母共26个,故利用str.find()和str.rfind()方法解决(参考他人)
str.find(str, beg=0, end=len(string)):检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
str.rfind(str, beg=0 end=len(string)):返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
sinCha = []
for i in "qwertyuiopasdfghjklzxcvbnm":
start = s.find(i)
end = s.rfind(i)
if start != -1 and start == end:
sinCha.append(start)
if sinCha:
return min(sinCha)
return -1
str.count()+str.index(),一行优雅写法(参考他人)
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])
算法题来自:https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/