LintCode 29: Interleaving String (DP字符串处理经典题)

  1. Interleaving String
    中文English
    Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.

Example
Example 1:

Input:
“aabcc”
“dbbca”
“aadbbcbcac”
Output:
true
Example 2:

Input:
“”
“”
“1”
Output:
false
Example 3:

Input:
“aabcc”
“dbbca”
“aadbbbaccc”
Output:
false
Challenge
O(n2) time or better

解法1:
DP。dp[i][j]表示s1的前i个字符和s2的前j个字符能否拼成s3的前i+j个字符。
代码如下:

class Solution {
public:
    /**
     * @param s1: A string
     * @param s2: A string
     * @param s3: A string
     * @return: Determine whether s3 is formed by interleaving of s1 and s2
     */
    bool isInterleave(string &s1, string &s2, string &s3) {
        int L = s1.size();
        int M = s2.size();
        int N = s3.size();
        if (N != L + M) return false;
        
        vector<vector<bool>> dp(L + 1, vector<bool>(M + 1, false));
        
        dp[0][0] = true;

        for (int i = 1; i <= L; ++i) {
            dp[i][0] = s3[i - 1] == s1[i - 1];
        }
        
        for (int i = 1; i <= M; ++i) {
            dp[0][i] = s3[i - 1] == s2[i - 1];
        }
        
        for (int i = 1; i <= L; ++i) {
            for (int j = 1; j <= M; ++j) {
                if (dp[i - 1][j]) {
                    if (s1[i - 1] == s3[i + j - 1]) dp[i][j] = true;
                } else if (dp[i][j - 1]) {
                    if (s2[j - 1] == s3[i + j - 1]) dp[i][j] = true;
                } else if (dp[i - 1][j - 1]) {
                    if (s1[i - 1] == s3[i + j - 2] && s2[j - 1] == s3[i + j - 1]) dp[i][j] = true;
                    else if (s1[i - 1] == s3[i + j - 1] && s2[j - 1] == s3[i + j - 2]) dp[i][j] = true;
                }
            }
        }
        
        return dp[L][M];
    }
    
};

解法2:解法1的else分支其实多余,因为前面两个分支已经cover了这个case。

class Solution {
public:
    bool isInterleave(string &s1, string &s2, string &s3) {
        int L = s1.size();
        int M = s2.size();
        int N = s3.size();
        if (N != L + M) return false;
        
        vector<vector<bool>> dp(L + 1, vector<bool>(M + 1, false));
        
        dp[0][0] = true;

        for (int i = 1; i <= L; ++i) {
            dp[i][0] = s3[i - 1] == s1[i - 1];
        }
        
        for (int i = 1; i <= M; ++i) {
            dp[0][i] = s3[i - 1] == s2[i - 1];
        }
        
        for (int i = 1; i <= L; ++i) {
            for (int j = 1; j <= M; ++j) {
                if (dp[i - 1][j]) {
                    if (s1[i - 1] == s3[i + j - 1]) dp[i][j] = true;
                } else if (dp[i][j - 1]) {
                    if (s2[j - 1] == s3[i + j - 1]) dp[i][j] = true;
                }
            }
        }
        
        return dp[L][M];
    }
    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值