简体   繁体   English

查找第一个不同的字符串

[英]Find first distinct string

I was having an interview for an internship. 我正在接受实习面试。 Interviewer asked following question. 面试官问了以下问题。

Given a stream of Strings, find the first distinct string(not repeated in stream). 给定字符串流,找到第一个不同的字符串(在流中不重复)。

For ex : "abc","xyz","abcd","abc" 例如:“ abc”,“ xyz”,“ abcd”,“ abc”

ans is "abc","abc","abc","xyz" ans是“ abc”,“ abc”,“ abc”,“ xyz”

I told the approach with map and sets, but the time complexity is O(nlogn) assuming String's hash value is calculated in O(1). 我告诉了使用map和set的方法,但是假设String的哈希值是在O(1)中计算的,则时间复杂度为O(nlogn)。 He constantly kept emphasizing to do better and told that the expected complexity is O(n). 他不断强调做得更好,并告诉我们预期的复杂度为O(n)。 I could not come up with solution and I was rejected. 我无法提出解决方案,但被拒绝了。 Please help me with an appraoch. 请帮我一个忙。

It can be solved with trie and queue. 可以使用trie和queue解决。

for string in text:
    if string not in trie:
        insert_in_trie(string)
        insert_in_queue(string)
    else:
        if not queue.empty():
            queue.pop()

    if queue.empty():
        print("No distinct character")
    else:
        print(queue.front())

Overall complexity will O(total length of strings) because insertion, deletion and peek in queue and trie will be O(length of string). 总体复杂度将为O(字符串的总长度),因为插入,删除和在队列中的偷看和trie将为O(字符串的长度)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM