LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]
题目: 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.
这个题目值得记录的原因除了自己的解法没有通过大集合以外,主要还在与对动态规划的理解。在这两个月研究算法的过程中,我发现自己更倾向于直观的理解,而抽象思维上相对较弱。我们以这道题做个例子。
直观上,我看到该题,就会去想,s1取一部分,s2取一部分,然后再s1取一部分,反复知道匹配完成s3,算法去模拟这样的操作。
而当s1和s3匹配了一部分的时候,剩下s1‘和剩下的s3‘与s2又是一个子问题。这样很容易写成一个递归,但是需要注意两点:
1. 递归方法中,我们总是拿s1首先去匹配s3,如果不匹配,直接返回false。这样做的原因是保持匹配是“交替”进行的;
2. 当出现既可以匹配s1,又可以匹配s2的时候,一样可以通过递归来解决,看下面的代码。
private boolean isInterleaveInternal(String s1, String s2, String s3){
if(s1.equals("")) {
return s2.equals("") && s3.equals("");
}
if(s1.equals(s3) && s2.endsWith("")) return true;
int i1 = 0;
int i2 = 0;
int i3 = 0;
if(s1.charAt(0) != s3.charAt(0)) return false;
while(i1 < s1.length() && i2 < s2.length() && i3 < s3.length() &&
s1.charAt(i1) == s3.charAt(i3)) {
i1++;
i3++;
//如果这里s2也可以匹配s3,那么我们立马递归进行匹配
if(s2.charAt(i2) == s3.charAt(i3) && isInterleaveInternal(s2.substring(i2), s1.substring(i1), s3.substring(i3)))
return true;
}
//接下来开始匹配s2
return isInterleaveInternal(s2, s1.substring(i1), s3.substring(i3));
}
所以在调用这个方法的时候,也比较复杂,需要保证一定是s1首先匹配s3.
public boolean isInterleave(String s1, String s2, String s3) {
// Start typing your Java solution below
// DO NOT write main() function
if(s1.length() + s2.length() != s3.length()) return false;
if(s1.equals("") || s2.equals("") || s3.equals("")) {
if(s3.equals("")) return s1.equals("") && s2.equals("");
else return s1.equals(s3) || s2.equals(s3);
}
if(s1.charAt(0) == s3.charAt(0)) {
if(s2.charAt(0) != s3.charAt(0)) {
return isInterleaveInternal(s1, s2, s3);
}else {
if(isInterleaveInternal(s1, s2, s3)) return true;
else return isInterleaveInternal(s2, s1, s3);
}
}else if(s2.charAt(0) == s3.charAt(0)) return isInterleave(s2, s1, s3);
else return false;
}
这个办法看上去蛮直观的,是我马上能想到的,而且也是收到前面递归方法的影响。
但是大集合会超时,而且不好的地方是主函数有挺多的条件判断,显得不够简洁。
于是我们参考了这里的动态规划方法。
动态规划矩阵matched[l1][l2]表示s1取l1长度(最后一个字母的pos是l1-1),s2取l2长度(最后一个字母的pos是l2-1),是否能匹配s3的l1+12长度。
那么,我们有
matched[l1][l2] = s1[l1-1] == s3[l1+l2-1] && matched[l1-1][l2] || s2[l2 - 1] == s3[l1+l2-1] && matched[l1][l2-1]
边界条件是,其中一个长度为0,另一个去匹配s3.
这里s1和s2交替出现的规律并不明显,所以没有直观地想到。
代码如下:
public boolean isInterleave2(String s1, String s2, String s3){
if(s1.length() + s2.length() != s3.length()) return false;
boolean[][] matched = new boolean[s1.length() + 1][s2.length() + 1];
matched[0][0] = true;
for(int i1 = 1; i1 <= s1.length(); i1++){
if(s3.charAt(i1-1) == s1.charAt(i1-1)) {
matched[i1][0] = true;
}else break;
}
for(int i2 = 1; i2 <= s2.length(); i2++){
if(s3.charAt(i2 - 1) == s2.charAt(i2 - 1)) {
matched[0][i2] = true;
}else break;
}
for(int i1 = 1; i1 <= s1.length(); i1++){
char c1 = s1.charAt(i1 - 1);
for(int i2 = 1; i2 <= s2.length(); i2++){
int i3 = i1 + i2;
char c2 = s2.charAt(i2 - 1);
char c3 = s3.charAt(i3 - 1);
if(c1 == c3){
matched[i1][i2] |= matched[i1 - 1][i2];
}
if(c2 == c3){
matched[i1][i2] |= matched[i1][i2 - 1];
}
}
}
return matched[s1.length()][s2.length()];
}
总结下:
1)递归能写出比较清晰简单的代码,但是有比较高的时间复杂度;
2)在递归不满足条件的情况下,动态规划是个比较好的选择;
3)一般来说,独立变量的个数决定动态规划的维度,例如l1和l2独立变化,所以用了二维动态规划。
LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]的更多相关文章
- LeetCode 笔记系列 19 Scramble String [合理使用递归]
题目: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty subs ...
- LeetCode(97) Interleaving String
题目 Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: ...
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...
- LeetCode 笔记系列五 Generate Parentheses
题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...
随机推荐
- python学习之while语句
while循环 1.简单的while循环while True: ")#这是一个简单的while循环,当等于True时会一直打印1 2.while执行多少次后退出 coun=0while Tr ...
- 关于 Oracle 的数据导入导出及 Sql Loader (sqlldr) 的用法
在 Oracle 数据库中,我们通常在不同数据库的表间记录进行复制或迁移时会用以下几种方法: 1. A 表的记录导出为一条条分号隔开的 insert 语句,然后执行插入到 B 表中2. 建立数据库间的 ...
- Oracle的select使用
1.select : 语法: select [distinct] {*,column [alias],...} from table 注:[]括起来的内容代表可有可无 * 代表所有列 distinct ...
- Trying to hack Redis via HTTP requests
Trying to hack Redis via HTTP requests Context Imagine than you can access a Redis server via HTTP r ...
- metasploit模块功能介绍
metasploit的模块构成及功能分析 转载自----http://forum.cnsec.org/thread-94704-1-1.html 今天我们介绍一下metasploit的基础架构和 市 ...
- PHP操作MySQL的常用函数
某些情况下(如html中),调用php的变量时,要给变量加{},若要使字符串变量加上引号,则还需要在{}外加引号 如: $sql="select * from admin where use ...
- Linux信号基础
Linux信号基础 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Linux进程基础一文中已经提到,Linux以进程为单位来 ...
- hdu3247Resource Archiver(ac自动机+spfa)
链接 这题没想到怎么做,问了下p队长,大悟.. 先求出任意两串的在trie树上的最短距离,期间是不能走到不合法的地方,我是用spfa求得,在更新和加入节点时判断一下是不是合法位置. 求出最短距离之后, ...
- HttpHelper类登录淘宝联盟并下载淘宝客订单xls
本次开发环境与工具如下:IE9.0浏览器 + IE抓包插件HttpWatch +WIN7 64位系统 + VS2005 IDE + .NET 2.0框架本想上传HttpWatch抓包插件,但由于文件超 ...
- Element is not currently visible and so may not be interacted with错误
用selenium定位时,碰到这种错误的原因: 此种问题的关键是在于用className和id都不唯一所以找不到对象 所以,碰到这种问题就换一种定位方式