97. Interleaving String

97. Interleaving String

题目

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.

解析

  • LeetCode(97) Interleaving String
    状态cache[i][j]表示,s1的前i个字符和s2的前j个字符是否能交叉构成s3的前i+j个字符
    初始化:
    cache[0][0] = True 因为两个空字符串可以组成空字符串
    边界情况是一个字符串为空,初始化只需判断另一个字符串和目标字符串前x为是否相等
    递推关系 cache[i][j] = (s1[i] == s3[i+j] and cache[i-1][j]) or (s2[j] == s3[i+j] and cache[i][j-1])

class Solution_97 {
public:
    bool isInterleave(string s1, string s2, string s3) {

        if (s3.length() != s1.length() + s2.length())
            return false;

        bool table[s1.length() + 1][s2.length() + 1];

        for (int i = 0; i < s1.length() + 1; i++)
        for (int j = 0; j < s2.length() + 1; j++){
            if (i == 0 && j == 0)
                table[i][j] = true;
            else if (i == 0)
                table[i][j] = (table[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
            else if (j == 0)
                table[i][j] = (table[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
            else
                table[i][j] = (table[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (table[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
        }

        return table[s1.length()][s2.length()];
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8835926.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞