lintcode -- 交叉字符串
来源:互联网 发布:python只能在c盘吗 编辑:程序博客网 时间:2024/06/05 07:54
给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。
比如 s1 = "aabcc" s2 = "dbbca"
- 当 s3 = "aadbbcbcac",返回 true.
- 当 s3 = "aadbbbaccc", 返回 false.
/*
思路:使用动态规划思想解决。
定义动态规划数组为dp[i][j], 其中s1取前i位,但是第i为之前的字符串也必须是构成s3的;s2取前j位,但是第J位之前的字符串也必须是构成s3的,是否能组成s3的前i+j位。
首先判断字符串s3是以s1或s2开头,如果对应的字符相等则赋值为true:假设s1为空,那么s2每一位跟s3匹配放入dp[0][j];假设s2为空,那么s1每一位跟s3匹配放入dp[i][0]。
*/
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length();
if (len1 + len2 != s3.length())
return false;
boolean[][] dp = new boolean[len1 + 1][len2 + 1];
dp[0][0] = true;
int i = 1, j = 1;
//如果s1与s3匹配
while (i <= len1 && s1.charAt(i - 1) == s3.charAt(i - 1)){
dp[i][0] = true;
i++;
}
//如果s2与s3匹配
while (j <= len2 && s2.charAt(j - 1) == s3.charAt(j - 1)){
dp[0][j] = true;
j++;
}
for (i = 1; i <= len1; i++) {
for (j = 1; j <= len2; j++) {
if ((dp[i - 1][j]==true && s1.charAt(i - 1) == s3.charAt(i + j - 1))
|| (dp[i][j - 1]==true && s2.charAt(j - 1) == s3.charAt(i + j - 1))){
dp[i][j] = true;
}
}
}
return dp[len1][len2];
}
}
- LintCode-交叉字符串
- LintCode(M)交叉字符串
- LintCode 29-交叉字符串
- LintCode 29 交叉字符串
- LintCode 交叉字符串
- lintcode -- 交叉字符串
- LintCode 交叉字符串
- lintcode 29. 交叉字符串
- lintcode interleaving-string 交叉字符串
- [Lintcode] Interleaving String 交叉字符串
- (lintcode)第29题交叉字符串
- lintcode 交叉链表
- 交叉字符串
- 交叉字符串
- 交叉字符串
- 交叉字符串
- 交叉字符串
- 交叉字符串
- bzoj 1649: [Usaco2006 Dec]Cow Roller Coaster 背包dp
- 利用shiro实现密码错误锁定账户功能
- cmd chcp命令切换字符格式 cmd重定向输出到文件出现中文乱码的处理方法
- iOS MonsterBall(怪物舞会)~demo
- matlab bwlabel
- lintcode -- 交叉字符串
- java数据结构与算法-双端链表实现队列
- 主成成分分析-PCA
- 每段时间Android开发10个知道(中级系列)-170815
- C++ txt 文件读取,并写入结构体中
- linux下安装gmpy2
- 二叉树深度
- Django的MVC架构(3)
- CF838A-Binary Blocks