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.
thinking:
(1)首先想到用递归,提交超时。
(2)这道题正确解法是 二维DP,状态转移方程:
很牛的解题:http://www.cnblogs.com/remlostime/archive/2012/11/25/2787297.html
f[i][j] = (f[i][j-1] && s2[j-1] == s3[i+j-1]) || (f[i-1][j] && s1[i-1] == s3[i+j-1]);
只有 s3的第 i+i-1 个字符与s1的第i-1个字符 或 s2的第j-1个字符相同时,才有可能有效。还要参考前面的结果。
code:
DP:
class Solution { private: bool f[1000][1000]; public: bool isInterleave(string s1, string s2, string s3) { if (s1.size() + s2.size() != s3.size()) return false; f[0][0] = true; for(int i = 1; i <= s1.size(); i++) //f[i][0]初始化 f[i][0] = f[i-1][0] && (s3[i-1] == s1[i-1]); for(int j = 1; j <= s2.size(); j++) //f[0][j]初始化 f[0][j] = f[0][j-1] && (s3[j-1] == s2[j-1]); for(int i = 1; i <= s1.size(); i++) for(int j = 1; j <= s2.size(); j++) f[i][j] = (f[i][j-1] && s2[j-1] == s3[i+j-1]) || (f[i-1][j] && s1[i-1] == s3[i+j-1]); return f[s1.size()][s2.size()]; } };
递归:超时
class Solution { public: bool isInterleave(string s1, string s2, string s3) { s1.push_back('0'); s2.push_back('0'); s3.push_back('0'); bool flag=false; check(s1,0,s2,0,s3,0,flag); return flag; } protected: void check(string s1,int i,string s2,int j,string s3,int k, bool &flag) { if(flag) return; if(s1[i]=='0'&&s2[j]=='0'&&s3[k]=='0') { flag=true; return; } if(s1[i]=='0'&&s2[j]=='0'&&s3[k]!='0') return; if((s1[i]!='0'&&s2[j]=='0'&&s3[k]=='0')||(s1[i]=='0'&&s2[j]!='0'&&s3[k]=='0')) return; if(s1[i]!=s3[k]&&s2[j]!=s3[k]) return; if(s1[i]==s3[k]) check(s1,i+1,s2,j,s3,k+1,flag); if(s2[j]==s3[k]) check(s1,i,s2,j+1,s3,k+1,flag); } };
leetcode || 97、Interleaving String
原文地址:http://blog.csdn.net/hustyangju/article/details/45092711