Interleaving String——是否由两个string交叉、DP

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.

Recurse:
Judge Small: Accepted! 
Judge Large: Time Limit Exceeded

 1 bool isInterleave(string s1, string s2, string s3) {  
 2         // Start typing your C/C++ solution below  
 3         // DO NOT write int main() function      
 4         if(s1.length() == 0) return s3 == s2;  
 5         if(s2.length() == 0) return s3 == s1;  
 6         if(s3.length() == 0) return s1.length() + s2.length() == 0;  
 7           
 8         if(s1[0] == s3[0] && s2[0] != s3[0])  
 9             return isInterleave(s1.substr(1), s2, s3.substr(1));  
10         else if(s1[0] != s3[0] && s2[0] == s3[0])  
11             return isInterleave(s1, s2.substr(1), s3.substr(1));  
12         else if(s1[0] == s3[0] && s1[0] == s3[0])  
13             return isInterleave(s1.substr(1), s2, s3.substr(1)) || isInterleave(s1, s2.substr(1), s3.substr(1));  
14         else  
15             return false;  
16     }  

2-dimension dp:

这是一个二维的动态规划,

s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac"

 1 class Solution {
 2 public:
 3     bool isInterleave(string s1, string s2, string s3) {
 4         if(s3.length()!=s1.length()+s2.length()) return false;
 5         vector<vector<bool>> res(s1.length()+1,vector<bool>(s2.length()+1, false));
 6         res[0][0]=true;
 7         for(int i=1;i<=s1.length();i++){
 8             res[i][0]=res[i-1][0]&&s1[i-1]==s3[i-1];
 9         }
10         for(int j=1;j<=s2.length();j++){
11             res[0][j]=res[0][j-1]&&s2[j-1]==s3[j-1];
12         }
13         for(int i=1;i<=s1.length();i++){
14             for(int j=1;j<=s2.length();j++){
15                 res[i][j]=(res[i-1][j]&&s1[i-1]==s3[i+j-1])||(res[i][j-1]&&s2[j-1]==s3[i+j-1]);
16             }
17         }
18         return res[s1.length()][s2.length()];
19     }
20     
21 };

 

posted @ 2017-06-20 19:59  鸭子船长  阅读(190)  评论(0编辑  收藏  举报