"""
97. Interleaving String
Description
HintsSubmissionsDiscussSolution
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

"""


class Solution:
    # BFS
    def isInterleave(self, s1, s2, s3):
        lx, ly, lz = len(s1), len(s2), len(s3)
        if lx + ly != lz:
            return False
        haved = [(0, 0)]
        visitedx = set()
        visitedy = set()
        while haved:
            x, y = haved.pop(0)
            if x + y == lz:
                return True
            # print(x,y)
            # if  x<lx and s1[x]==s3[x+y] and (x,y) not in visited :
            if x < lx and s1[x] == s3[x + y] and (x, y) not in visitedx:
                haved.append((x + 1, y))
                visitedx.add((x, y))
                # print('x',x,y)
            # if y<ly and s2[y]==s3[x+y] and (x,y) not in visited:
            if y < ly and s2[y] == s3[x + y] and (x, y) not in visitedy:
                haved.append((x, y + 1))
                visitedy.add((x, y))
                # print('y',x,y)
        return False


if __name__ == '__main__':
    s1 = "a"
    s2 = ""
    s3 = "a"
    # s1 = "aabcc"
    # s2 = "dbbcc"
    # aabc
    # dbbc
    # s3 = "aadbbcbcac"
    # s3 = "aadbbbaccc",
    s1 = "a"
    s2 = "b"
    s3 = "a"
    s1 = "abbbbbbcabbacaacccababaabcccabcacbcaabbbacccaaaaaababbbacbb"
    s2 = "ccaacabbacaccacababbbbabbcacccacccccaabaababacbbacabbbbabc"
    s3 = "cacbabbacbbbabcbaacbbaccacaacaacccabababbbababcccbabcabbaccabcccacccaabbcbcaccccaaaaabaaaaababbbbacbbabacbbacabbbbabc"
    s1 = "aa"
    s2 = "ab"
    s3 = "aaba"
    st = Solution()
    out = st.isInterleave(s1, s2, s3)
    print(out)

龙仔
12 声望4 粉丝