https://oj.leetcode.com/problems/interleaving-string/
刚开始用递归做,但是超时了
class Solution { public: bool flag; bool isInterleave(string s1, string s2, string s3) { flag = false; if(s1.size() + s2.size() != s3.size()) return flag; subIsInterleave(s1,s2,s3,0,0,0); return flag; } void subIsInterleave(string &s1, string &s2, string &s3, int p1, int p2, int p3) { if(p1 == s1.size() && p2 == s2.size() && p3 == s3.size()) { flag = true; return; } if(!(p1 <= s1.size() && p2 <= s2.size() && p3 < s3.size())) return; if(s3[p3] != s1[p1] && s3[p3] != s2[p2]) { return; } if(p1 < s1.size() && s3[p3] == s1[p1] && flag == false) subIsInterleave(s1,s2,s3,p1 + 1, p2,p3 + 1); if(p2 < s2.size() && s3[p3] == s2[p2] && flag == false) subIsInterleave(s1,s2,s3,p1,p2+1,p3 + 1); } };
按照二维动态规划的思路,用两层for循环做
记 flag[i][j] 为 s1[0,i] s2[0,j] 匹配 s3[0,i+j] 则:
flag[i][j] = s1[i-1] == s3[i+j-1] && flag[i-1][j] || s2[j-1] == s3[i+j-1] && flag[i][j-1];
代码如下:
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s3.size() != s1.size() + s2.size()) return false; vector<vector<bool> > flag(s1.size()+1, vector<bool>(s2.size()+1, true)); // init for(int i = 1; i < s1.size() + 1; i++) flag[i][0] = flag[i-1][0] && (s1[i-1] == s3[i-1]); for(int j = 1; j < s2.size() + 1; j++) flag[0][j] = flag[0][j-1] && (s2[j-1] == s3[j-1]); for(int i = 1; i < s1.size() + 1; i++) for(int j = 1; j < s2.size() + 1; j++) { flag[i][j] = ((s1[i-1] == s3[i+j-1]) && flag[i-1][j]) || ((s2[j-1] == s3[i+j-1]) && flag[i][j-1]); } return flag[s1.size()][s2.size()]; } };