All possible ways to interleave two strings

前端 未结 5 606
傲寒
傲寒 2021-01-03 22:30

I am trying to generate all possible ways to interleave any two arbitrary strings in Python.

For example: If the two strings are \'ab\' and \'cd\'

5条回答
  •  时光说笑
    2021-01-03 23:26

    The Idea

    Let the two strings you want to interleave be s and t. We will use recursion to generate all the possible ways to interleave these two strings.

    If at any point of time we have interleaved the first i characters of s and the first j characters of t to create some string res, then we have two ways to interleave them for the next step-

    1. Append the i+1 th character of s to res
    2. Append the j+1 th character of t to res

    We continue this recursion till all characters of both the strings have been used and then we store this result in a list of strings lis as in the code below.

    The Code

    def interleave(s, t, res, i, j, lis):
        if i == len(s) and j == len(t):
            lis.append(res)
            return
        if i < len(s):
            interleave(s, t, res + s[i], i + 1, j, lis)
        if j < len(t):
            interleave(s, t, res + t[j], i, j + 1, lis)
    
    l = []
    s = "ab"
    t = "cd"
    interleave(s, t, "", 0, 0, l)
    print l
    

    Output

    ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']
    

    This implementation is as efficient as we can get (at least asymptotically) since we never generate the same string twice.

提交回复
热议问题