热线电话:13121318867

登录
2019-03-17 阅读量: 636
如何从字符流中查找第一个非重复字符

给定一个字符串,从流中找到第一个非重复字符。你需要在任何时刻告诉O(1)时间内的第一个非重复字符。
如果我们遵循讨论的第一种方法,那么我们需要存储流,以便我们可以再次遍历它以在任何时刻找到第一个非重复字符。如果我们使用之前讨论的扩展方法,我们需要在每次查询第一个非重复元素时遍历count数组。我们可以随时从流中找到第一个非重复字符,而无需遍历任何数组。

# A Python program to find first non-repeating character from

# a stream of characters

MAX_CHAR = 256

def findFirstNonRepeating():

# inDLL[x] contains pointer to a DLL node if x is present

# in DLL. If x is not present, then inDLL[x] is NULL

inDLL = [] * MAX_CHAR

# repeated[x] is true if x is repeated two or more times.

# If x is not seen so far or x is seen only once. then

# repeated[x] is false

repeated = [False] * MAX_CHAR

# Let us consider following stream and see the process

stream = "geeksforgeeksandgeeksquizfor"

for i in xrange(len(stream)):

x = stream[i]

print "Reading " + x + " from stream"

# We process this character only if it has not occurred

# or occurred only once. repeated[x] is true if x is

# repeated twice or more.s

if not repeated[ord(x)]:

# If the character is not in DLL, then add this

# at the end of DLL

if not x in inDLL:

inDLL.append(x)

else:

inDLL.remove(x)

if len(inDLL) != 0:

print "First non-repeating character so far is ",

print str(inDLL[0])

# Driver program

findFirstNonRepeating()

# This code is contributed by BHAVYA JAIN

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子