Leetcode 97. 交错字符串

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        if (s1.size() + s2.size() != s3.size()) return false;
        vector<bool> dp(s2.size() + 1, false);
        dp[0] = true;
        for (int j = 1; j <= s2.size(); ++j)
            dp[j] = (dp[j - 1] && s2[j - 1] == s3[j - 1]);
        for (int i = 1; i <= s1.size(); ++i) {
            dp[0] = dp[0] & (s1[i - 1] == s3[i - 1]);
            for (int j = 1; j <= s2.size(); ++j)
                dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) |
                (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);
        }
        return dp[s2.size()];
    }
};

压缩矩阵

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        if (s1.size() + s2.size() != s3.size()) return false;
        vector<bool> dp(s2.size() + 1, false);
        dp[0] = true;
        for (int j = 1; j <= s2.size(); ++j)
            dp[j] = (dp[j - 1] && s2[j - 1] == s3[j - 1]);
        for (int i = 1; i <= s1.size(); ++i) {
            dp[0] = dp[0] & (s1[i - 1] == s3[i - 1]);
            for (int j = 1; j <= s2.size(); ++j)
                dp[j] = (dp[j] && s1[i - 1] == s3[i + j - 1]) |
                (dp[j - 1] && s2[j - 1] == s3[i + j - 1]);
        }
        return dp[s2.size()];
    }
};

你可能感兴趣的:(Leetcode 97. 交错字符串)