leetcode Interleaving String
2015-06-21 19:35
453 查看
题目
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.
题目来源:https://leetcode.com/problems/interleaving-string/
分析
动态规划。构造二维辅助数组dp[len1+1][len2+1]。dp[i+1][j+1] == true 表示s1[0…i]和s2[0…j]能够构造成s3[0…i+j+1]。
递推公式:
dp[i+1][j+1] = (dp[i+1][j] && (s3.at(i+j+1) == s2.at(j))) || (dp[i][j+1] && s3.at(i+j+1) == s1.at(i));
代码
[code]class Solution { public: bool isInterleave(string s1, string s2, string s3) { int len1 = s1.length(); int len2 = s2.length(); int len3 = s3.length(); if(len3 != len1 + len2) return false; vector<vector<bool> > dp(len1 + 1, vector<bool> (len2 + 1, false)); dp[0][0] = true; for(int i = 0; i < len1; i++) dp[i+1][0] = (s1.at(i) == s3.at(i)) && dp[i][0]; for(int i = 0; i < len2; i++) dp[0][i+1] = (s2.at(i) == s3.at(i)) && dp[0][i]; for(int i = 0; i < len1; i++){ for(int j = 0; j < len2; j++){ dp[i+1][j+1] = (dp[i+1][j] && (s3.at(i+j+1) == s2.at(j))) || (dp[i][j+1] && s3.at(i+j+1) == s1.at(i)); } } return dp[len1][len2]; } };
相关文章推荐
- 教你如何把excel中的数据导入到Mysql中
- Android学习笔记之AndroidManifest.xml文件解析
- readwrite,readonly,assign,retain,copy,nonatomic属性的作用
- CSS3系列二(媒体支持、文字与字体相关样式、盒相关样式)
- Windows Phone 8.1中页面导航切换动画特效
- 使用Socket实现简单聊天
- android ActionBar
- [HDU 1016]--Prime Ring Problem(回溯)
- oc 的优缺点
- 【牛腩】div+css模型
- javascript:深入理解js闭包
- 我看我自己系列——我毁掉的生活我痛苦的地方。
- Count and Say
- SimpleDateFormat使用特定的解释
- POJ 2481 Cows【树状数组】
- SQL like使用 模糊查询
- ubuntu系统学习之:64位ubuntu系统安装32位兼容库ia32-libs的方法
- 黑马程序员--Java学习日记之面试问题汇总,感谢黑马论坛!
- bootstrap折叠内容
- AndroidStudio中百度地图接口使用配置相关总结