How to find smallest substring which contains all characters from a given string?

后端 未结 15 1100
灰色年华
灰色年华 2020-12-02 07:36

I have recently come across an interesting question on strings. Suppose you are given following:

Input string1: \"this is a test string\"
Input strin         


        
15条回答
  •  萌比男神i
    2020-12-02 08:26

    I've implemented it using Python3 at O(N) efficiency:

    def get(s, alphabet="abc"):
        seen = {}
        for c in alphabet:
            seen[c] = 0
        seen[s[0]] = 1
        start = 0
        end = 0
        shortest_s = 0
        shortest_e = 99999
        while end + 1 < len(s):
            while seen[s[start]] > 1:
                seen[s[start]] -= 1
                start += 1
            # Constant time check:
            if sum(seen.values()) == len(alphabet) and all(v == 1 for v in seen.values()) and \
                    shortest_e - shortest_s > end - start:
                shortest_s = start
                shortest_e = end
            end += 1
            seen[s[end]] += 1
        return s[shortest_s: shortest_e + 1]
    
    
    print(get("abbcac")) # Expected to return "bca"
    

提交回复
热议问题