码迷,mamicode.com
首页 > 其他好文 > 详细

【Lintcode】029.Interleaving String

时间:2017-05-21 10:58:15      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:pre   blog   vector   ane   adb   int   min   and   rmi   

题目:

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.

题解:

Solution 1 ()

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

Solution  2 ()

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

  DFS

Solution 3 ()

  BFS

Solution 4 ()

 

【Lintcode】029.Interleaving String

标签:pre   blog   vector   ane   adb   int   min   and   rmi   

原文地址:http://www.cnblogs.com/Atanisi/p/6884025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!