find first non-repeating character in string
问题描述如下:
Find the first non repetitive character in a string?
也就是找出字符串中第一个不重复的字符
比如,字符串"asabc"中,第一个不重复的字符就是s
有以下两种方法
方法一:利用一个字典和一个列表解决,字典记录每个字符出现的次数,列表记录出现过的字符,从前到后遍历这个string
- 遇到新字符(字典中没有的key),在字典中添加key为该字符,value为1,列表中append该字符
- 遇到出现过的字符(字典中有该key),字典中该key的value加1
然后,遍历列表,打印出value为1的字符即可
代码如下
def findFirstNonRepeating(s): count = {} characters = [] for c in s: if count.has_key(c): count[c] += 1 else: characters.append(c) count[c] = 1 for c in characters: if count.get(c) == 1: return c return None
方法二:用字符替换
取当前字符串的第一个字符,然后在整个字符串中替换该字符为空字符,记录替换前字符串长度为len1,替换后字符串长度为len2
- 如果len1-len2等于1,那么可以确定该字符只有一个,返回该字符
- 如果len1-len2大于1,那么用替换后的字符串继续循环
代码如下
def findFirstNonRepeating(s): while s: len1 = len(s) ch = s[0] s = s.replace(ch, '') len2 = len(s) if len1 - 1 == len2: return ch return None