[leetcode/lintcode 题解] 阿里算法面试真题:交叉字符串

描述
给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。

在线评测地址:领扣题库官网

样例1
输入:
"aabcc"
"dbbca"
"aadbbcbcac"
输出:
true
样例2
输入:
""
""
"1"
输出:
false
样例3
输入:
"aabcc"
"dbbca"
"aadbbbaccc"
输出:
false

算法:动态规划

动态规划。 dpi代表由s1的前i个字母和s2的前j个字母是否能构成当前i+j个字母。 然后状态转移即可。(看第i+j+1个是否能被s1的第i+1个构成或被s2的第j+1个构成)

class Solution:
    """
    @params s1, s2, s3: Three strings as description.
    @return: return True if s3 is formed by the interleaving of
             s1 and s2 or False if not.
    @hint: you can use [[True] * m for i in range (n)] to allocate a n*m matrix.
    """
    def isInterleave(self, s1, s2, s3):
        # write your code here
        if s1 is None or s2 is None or s3 is None:
            return False
        if len(s1) + len(s2) != len(s3):
            return False

        interleave = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)]
        interleave[0][0] = True
        for i in range(len(s1)):
            interleave[i + 1][0] = s1[:i + 1] == s3[:i + 1]
        for i in range(len(s2)):
            interleave[0][i + 1] = s2[:i + 1] == s3[:i + 1]

        for i in range(len(s1)):
            for j in range(len(s2)):
                interleave[i + 1][j + 1] = False
                if s1[i] == s3[i + j + 1]:
                    interleave[i + 1][j + 1] = interleave[i][j + 1]
                if s2[j] == s3[i + j + 1]:
                    interleave[i + 1][j + 1] |= interleave[i + 1][j]
        return interleave[len(s1)][len(s2)]

更多题解参考:九章官网solution

上一篇:JQuery JCshare 0.1 分享插件


下一篇:C++标准pdf 分享