关闭

#29 Interleaving String

标签: lintcodedynamic programming
41人阅读 评论(0) 收藏 举报
分类:

题目描述:

Given three strings: s1s2s3, determine whether s3 is formed by the interleaving of s1 and s2.

Example

For s1 = "aabcc", s2 = "dbbca"

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

O(n2) time or better

题目思路:

这题也是经典的dp之一。我们可以设dp[i][j]为s1前i-1个char和s2前j-1个char是s3 i+j-1的interleaving。那么,dp方程为dp[i][j]为true的选择有两种:一种是dp[i-1][j]为true并且s1的第i个char和s3的第i+j个char相等;还有一种是p[i][j-1]为true并且s2的第j个char和s3的第i+j个char相等。

Mycode(AC = 23ms):

class Solution {
public:
    /**
     * Determine whether s3 is formed by interleaving of s1 and s2.
     * @param s1, s2, s3: As description.
     * @return: true of false.
     */
    bool isInterleave(string s1, string s2, string s3) {
        // write your code here
        if (s1.size() + s2.size() != s3.size()) return false;
        
        vector<vector<bool>> dp(s1.size() + 1, vector<bool>(s2.size() + 1, false));
        
        dp[0][0] = true;
        // initialize dp[i][0] and dp[0][i]
        for (int i = 1; i <= s1.size(); i++) {
            dp[i][0] = dp[i - 1][0] && s3[i - 1] == s1[i - 1];
        }
        for (int i = 1; i <= s2.size(); i++) {
            dp[0][i] = dp[0][i - 1] && s3[i - 1] == s2[i - 1];
        }
        
        // do dp
        for (int i = 1; i <= s1.size(); i++) {
            for (int j = 1; j <= s2.size(); j++) {
                dp[i][j] = (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) ||
                           (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
            }
        }
        
        return dp[s1.size()][s2.size()];
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11918次
    • 积分:2240
    • 等级:
    • 排名:第16771名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档