在本节中,我们将从字符串或字符流中找到第一个唯一的或非重复的字符。有多种方法可以解决此问题。我们将尝试为相同的字符流创建两个不同的程序。
def firstNonRepeatingChar(str1): char_order = [] counts = {} for c in str1: if c in counts: counts[c] += 1 else: counts[c] = 1 char_order.append(c) for c in char_order: if counts[c] == 1: return c return None print(firstNonRepeatingChar('PythonforallPythonMustforall')) print(firstNonRepeatingChar('nhooofordeveloper')) print(firstNonRepeatingChar('AABBCC'))
M u None
上面的程序给出了O(n)解。在上面的程序中,我们首先循环遍历字符串一次。找到新字符后,将其存储在值为1的counts对象中,并将其附加到char_order。当遇到重复的字符时,我们将count的值增加1。最后,我们遍历char_order直到在char_order中找到一个值为1的字符并将其返回。
s = "nhooofordeveloper" while s != "": slen0 = len(s) ch = s[0] s = s.replace(ch, "") slen1 = len(s) if slen1 == slen0-1: print ("First non-repeating character is: ",ch) break; else: print ("找不到唯一的角色!")
First non-repeating character is: u