一、问题描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
方法一:
1.代码和思路
因为字符串是不可变的,这里我们只能创建一个list来记录列表中是否存在其重复
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
n=len(s)
s_list=[0]*n
i=0
while i<n:
if i<n and s_list[i]==0:
for j in range(i+1,n):
if s_list[j]==1:
continue
if s[j]==s[i]:
s_list[i]=s_list[j]=1
if s_list[i]==0:
return i
i += 1
return -1
2.运行结果来看并不好
方法二:
1.代码和思路
先构建一个字典用来存放s中的元素的出现频率,然后从头开始编遍历s,发现s中的元素中在字典中的value是1就返回该元素的位置
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
s_dict={}
for st in s:
if st in s_dict:
s_dict[st] += 1
else:
s_dict[st]=1
for i in range(len(s)):
if s_dict[s[i]]==1:
return i
return -1
2.运行结果