最简单得想法就是把字符串里每个出现的字符都用字典 hash的形式把key(),value() 记录下来,然后
方法一:哈希表
1、遍历字符串,将字符当成哈希表中的key,value区分第一次出现和多次出现;
2、遍历字符串,拿到第一个在哈希表中的value为1的字符,通过 s.index()或者s.find()返回索引,
记住return是从被调函数返回到主调函数继续执行,返回时可附带一个返回值,,所以一旦执行了后面的代码就不执行了,所以自然而然后面的循环也跳出了。
而break,continue是用来单独跳出循环的
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dic = dict()
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in s:
if dic[i] == 1:
return s.index(i)
return -1
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dic = dict()
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in s:
if dic[i] == 1:
return s.index(i)
return -1
也可以不用s.index()或者s.find()函数
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dic = dict()
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in range(len(s)):
if dic[s[i]]==1:
return i
return -1
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dic = dict()
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in range(len(s)):
if dic[s[i]]==1:
return i
return -1