标签:style blog color for io div
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[i][j]表示s1[0...i]和s2[0...j]是否满足s3[i+j]匹配的要求。
初始条件:dp[0][0]=true;
状态转移方程:dp[i][0]=(dp[i-1][0]&&s1[i-1]==s3[i-1])、dp[0][j]=(dp[0][j-1]&&s2[j-1]==s3[j-1]);dp[i][j]=(dp[i-1][j]&&(s1[i-1]==s3[i+j-1]))||(dp[i][j-1]&&(s2[j-1]==s3[i+j-1])
最后返回dp[n1][n2]就是所要求的结果。
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int n1=s1.size(); int n2=s2.size(); int n3=s3.size(); if(n1+n2!=n3) return false; vector<vector<bool> > dp(n1+1,vector<bool>(n2+1,false)); dp[0][0]=true; for(int i=1;i<=n1;i++) { dp[i][0]=dp[i-1][0] && (s3[i-1]==s1[i-1]); } for(int j=1;j<=n2;j++) { dp[0][j]=dp[0][j-1]&&(s3[j-1]==s2[j-1]); } for(int i=1;i<=n1;i++) { for(int j=1;j<=n2;j++) { dp[i][j]=(dp[i-1][j]&&(s1[i-1]==s3[i+j-1]))||(dp[i][j-1]&&(s2[j-1]==s3[i+j-1])); } } return dp[n1][n2]; } };
Interleaving String,布布扣,bubuko.com
标签:style blog color for io div
原文地址:http://www.cnblogs.com/awy-blog/p/3815307.html