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.
解题思路:很经典的一道DP题。table[i][j]表示字符串s1的位置位i,s2的位置位j时能否用s1[0..i-1],s2[0...j-1]拼成s3[0...i+j-1]。初始化时table[0][0]=1表示全都为空时,可以完成。
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.length()+s2.length()!=s3.length())return false; vector<vector<int> >table(s1.length()+1,vector<int>(s2.length()+1,0)); for(int i=0;i<s1.length()+1;i++) for(int j=0;j<s2.length()+1;j++) if(i==0&&j==0)table[i][j]=1; else if(i==0)table[i][j]=(table[i][j-1]&&s2[j-1]==s3[j-1]); else if(j==0)table[i][j]=(table[i-1][j]&&s1[i-1]==s3[i-1]); else table[i][j]=table[i-1][j]&&s1[i-1]==s3[i+j-1]||table[i][j-1]&&s2[j-1]==s3[i+j-1]; return table[s1.length()][s2.length()]; } };
时间: 2024-11-05 15:17:27