题目: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.
题意就是s3能否用s1和s2交错混合组成,字符之间的相对顺序不能改变。
用动态规划做,dp【i】【j】表示s3的前(i+j)个字符能否用s1的前i个字符和s2的前j个字符组成。递推不太复杂,看代码了。
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int l1=s1.size(),l2=s2.size(),l3=s3.size(); if(l1+l2!=l3)return false; bool dp[1000][1000]; for(int i=0;i<=l1;++i)for(int j=0;j<=l2;++j) { if(i==0&&j==0)dp[0][0]=true; else if(i==0)dp[0][j]=dp[0][j-1]&(s2[j-1]==s3[j-1]); else if(j==0)dp[i][0]=dp[i-1][0]&(s1[i-1]==s3[i-1]); else { dp[i][j]=(dp[i][j-1]&(s2[j-1]==s3[i+j-1])); dp[i][j]|=(dp[i-1][j]&(s1[i-1]==s3[i+j-1])); } } return dp[l1][l2]; } };