给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:可以假定该字符串只包含小写字母。
Python代码实现:
判断第一个字符是否唯一,不唯一就全删光,继续判断第一个字符,直到找出,
如果没有就返回-1
但超出时间限制:
class Solution:
def firstUniqChar(self, s):
ls = s[:]
s= list(s)
lenth = len(s)
while lenth>0:
k = s[0]
s.remove(k)
lenth -=1
if k not in s:
return ls.index(k)
else:
while k in s:
s.remove(k)
lenth -= 1
return -1
改变一下思路:用双重循环,判断有没有相等的。
class Solution:
def firstUniqChar(self, s):
length = len(s)
for i in range(length):
for j in range(length):
if s[i] == s[j] and i != j:
break # 提前中断可以提高效率
elif j == length-1 :
return i
return -1
将字符串 转换成 列表, 再用字典统计每个元素的次数,将字典的每个键 放到一个数组的排好序,按照这个次数来找出第一个次数为 1 的字符。
class Solution:
def firstUniqChar(self, s):
number= []
dic = {}
for i in range(len(s)):
if s[i] not in number:
number.append(s[i])
dic[s[i]] = 1
else:
dic[s[i]] += 1
for j in range(len(number)):
if dic.get(number[j]) == 1:
for k in range(len(s)):
if s[k] == number[j]:
return k
return -1
使用collection模块的Counter类:
class Solution(object):
def firstUniqChar(self, s):
dic=collections.Counter(s)#使用字典
for i in range(len(s)):
if dic[s[i]]==1:#如果字典中value为1
return i
return -1