题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
http://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
我写完后发现好像还没有人这么提出过一个这样的思路:
1、采用set函数,直接建立一个不含重复字母的集合;
2、遍历s字符串中的所有字母,采用enumerate()函数同步返回索引index与字母i;
3、若i在set集合中,说明i必然是第一次出现,此时先从set中移除i,防止下一次再搜索,然后从字符串s中切割出index+1至末尾的字符串,因为之前的字符串一定不可能有i的重复项(因为我们的遍历顺序就是自左向右的)
4、若3中找到了i的重复项,则跳过循环,按照步骤2、3重新比对s中的下一个字母,反之,则直接return 步骤2中的index即可;
5、若遍历完s后依旧没有找到不重复项,则在代码末尾return -1
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
s_set = set(s) # 用set记录从未查询过的字母
for index, i in enumerate(s):
if i in s_set:
s_set.remove(i)
isonlyone = True
for j in s[index+1:]:
if i == j:
isonlyone = False
break
if isonlyone == True:
return index
else:
continue
return -1
# write code here
