Algorithm to find the minimum length of substring having all characters of other string

前端 未结 4 927
我寻月下人不归
我寻月下人不归 2021-02-04 18:15

I have a two strings:
string1 - hello how are you,
String2 - olo (including space character)

Output: lo ho ( hello

4条回答
  •  孤独总比滥情好
    2021-02-04 18:53

    I would calculate positions of characters from string2 within string1 and then pick the permutation with minimum distance between lowest and highest character position:

    #          positions are:
    #          01234567890123456
    string1 = 'hello how are you'
    string2 = 'olo'
    
    # get string1 positions for each character from set(string2)
    positions = {'o': [4, 7, 15],
                 'l': [2, 3]}
    
    # get all permutations of positions (don't repeat the same element)
    # then pick the permutation with minimum distance between min and max position
    # (obviously, this part can be optimized, this is just an illustration)
    permutations = positions['o'] * positions['l'] * positions['o']
    permutations = [[4,2,7], [4,3,7], [4,2,15], ...]
    the_permutation = [4,3,7]
    
    # voilà
    output = string1_without_spaces[3:7]
    

提交回复
热议问题