Answer to Question #218177 in Python for Krish

Question #218177

Write a program for interleave strings


1
Expert's answer
2021-07-19T00:36:45-0400
def isInterleave(s1, s2, s3):
    len_s1, len_s2, len_s3 = len(s1), len(s2), len(s3)
    if len_s1 + len_s2 != len_s3:
        return False
    DP = [[False for i in range(len_s2 + 1)] for j in range(len_s1 + 1)]
    for i in range(len_s1 + 1):
        for j in range(len_s2 + 1):
            if i == 0 and j == 0:
                DP[i][j] = True
            elif i == 0:
                DP[i][j] = (DP[i][j-1] and s2[j-1] == s3[i+j-1])
            elif j == 0:
                DP[i][j] = (DP[i-1][j] and s1[i-1] == s3[i+j-1])
            else:
                DP[i][j] = (DP[i-1][j] and s1[i-1] == s3[i+j-1]) or (DP[i][j-1] and s2[j-1] == s3[i+j-1])
    return DP[len_s1][len_s2]


first_string, second_string, third_string = input('First string: '), input('Second string: '), input('Third string: ')
if isInterleave(first_string, second_string, third_string):
    print('Third string is an interleaving of first and second strings')
else:
    print("It is not possible to get third string by interleaving first and second strings")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS