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

后端 未结 15 1133
灰色年华
灰色年华 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
    慢半拍i (楼主)
    2020-12-02 08:04

    Here's an O(n) solution. The basic idea is simple: for each starting index, find the least ending index such that the substring contains all of the necessary letters. The trick is that the least ending index increases over the course of the function, so with a little data structure support, we consider each character at most twice.

    In Python:

    from collections import defaultdict
    
    def smallest(s1, s2):
        assert s2 != ''
        d = defaultdict(int)
        nneg = [0]  # number of negative entries in d
        def incr(c):
            d[c] += 1
            if d[c] == 0:
                nneg[0] -= 1
        def decr(c):
            if d[c] == 0:
                nneg[0] += 1
            d[c] -= 1
        for c in s2:
            decr(c)
        minlen = len(s1) + 1
        j = 0
        for i in xrange(len(s1)):
            while nneg[0] > 0:
                if j >= len(s1):
                    return minlen
                incr(s1[j])
                j += 1
            minlen = min(minlen, j - i)
            decr(s1[i])
        return minlen
    

提交回复
热议问题