[LeetCode] 037: Interleaving String

来源:互联网 发布:免费视频监控软件 编辑:程序博客网 时间:2024/06/01 10:22
[Problem]

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.


[Solution]

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// special cases
int len1 = s1.size(), len2 = s2.size(), len3 = s3.size();
if(len1 + len2 != len3)return false;
if(len3 == 0)return true;

// initial
bool **dp = new bool*[len1+1];
for(int i = 0; i <= len1; ++i){
dp[i] = new bool[len2+1];
}
dp[len1][len2] = true;

// set the last row except the last column
for(int i = len2-1; i >= 0; --i){
if(s2[i] == s3[len3-len2+i] && dp[len1][i+1]){
dp[len1][i] = true;
}
else{
dp[len1][i] = false;
}
}

// set the last column except the last row
for(int i = len1-1; i >= 0; --i){
if(s1[i] == s3[len3-len1+i] && dp[i+1][len2]){
dp[i][len2] = true;
}
else{
dp[i][len2] = false;
}
}

// dp
for(int i = len1-1; i >= 0; --i){
for(int j = len2-1; j >= 0; --j){
if((s1[i] == s3[i+j] && dp[i+1][j]) || (s2[j] == s3[i+j] && dp[i][j+1])){
dp[i][j] = true;
}
else{
dp[i][j] = false;
}
}
}
return dp[0][0];
}
};

说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击