首页 > 代码库 > LeetCode:Interleaving String
LeetCode:Interleaving String
Given s1, s2,s3, find whether s3 is formed by the interleaving of s1 ands2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
解题思路:
如果熟悉动态规划的LCS和ED问题的话,不难看出这是个dp题目.首先,我们定义如下状态:
dp[i+1][j+1]:表示s1[0...i]与s2[0...j]能否交替形成s3[0...i+j+1]部分.
状态转移方程:
dp[i+1][j+1] = (dp[i][j+1] && s1[i] == s3[i+j+1]) | (dp[i+1][j] && s2[j] == s3[i+j+1]);
解题代码:
class Solution { public: bool isInterleave(string s1, string s2, string s3) { int m = s1.size(), n = s2.size(); if (m + n != s3.size()) return false; bool dp[m+1][n+1]; dp[0][0] = true; //初始化边界. for (int i = 0; i < n; ++i) dp[0][i+1] = dp[0][i] && s2[i] == s3[i]; for (int i = 0; i < m; ++i) dp[i+1][0] = dp[i][0] && s1[i] == s3[i]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) dp[i+1][j+1] = (dp[i][j+1] && s1[i] == s3[i+j+1]) | (dp[i+1][j] && s2[j] == s3[i+j+1]); return dp[m][n]; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。