题目: Given s1s2s3, 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 [动态规划的抽象]的更多相关文章

  1. LeetCode 笔记系列 19 Scramble String [合理使用递归]

    题目: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty subs ...

  2. LeetCode(97) Interleaving String

    题目 Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: ...

  3. 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 ...

  4. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

  5. LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

    题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...

  6. 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 ...

  7. 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 ...

  8. LeetCode 笔记系列五 Generate Parentheses

    题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...

  9. LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

随机推荐

  1. [课程设计]Scrum 1. 9 多鱼点餐系统开发进度(最后页面完善&修复BUG&用户测试反馈)

    [课程设计]Scrum 1. 9 多鱼点餐系统开发进度(最后页面完善&修复BUG&用户测试) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢 ...

  2. java语言的认识

    class Hello{ public static void main(String [] args) { System.out.println("Hello Word 你好") ...

  3. NSDate获取当前时区的时间

    [NSDate date]获取的是GMT时间,要想获得某个时区的时间,以下代码可以解决这个问题 NSDate *date = [NSDate date]; NSTimeZone *zone = [NS ...

  4. python(七)字符串格式化、生成器与迭代器

    字符串格式化 Python的字符串格式化有两种方式:百分号方式.format方式 1.百分号的方式 %[(name)][flags][width].[precision]typecode (name) ...

  5. Oracle、Microsoft SQL Server、Mysql

    数据库对比.----1.Oracle:最贵,功能最多,安装最不方便,Oracle环境里的其他相关组件最多,支持平台数量一般,使用中等方便,开发中等方便,运维中等方便,不开源,速度最慢,最安全.---- ...

  6. MYSQL转换JSON

    http://51strive.com/ <!DOCTYPE html><html><head><meta charset="UTF-8" ...

  7. 解决T400\T500\W500等安装win10驱动后黑屏问题

    T400.W500.T500等机型有双显卡的机型,在安装WIn10后会在驱动后黑屏,但可见启动画面: 原因:没有对应的双显卡驱动程序,导致系统无法正确识别显卡: 解决方法:开机按F1进入Bios,在显 ...

  8. Windows里面的hosts文件

    一.什么是Hosts文件? hosts文件是一个用于储存计算机网络中各节点信息的计算机文件.这个文件负责将主机名映射到相应的IP地址.hosts文件通常用于补充或取代网络中DNS的功能.和DNS不同的 ...

  9. M1卡介绍

    本文整理自网络. M1卡是指菲利浦下属子公司恩智浦出品的芯片缩写,全称为NXP Mifare1系列,常用的有S50及S70两种型号,目前都有国产芯片与其兼容,属于非接触式IC卡.最为重要的优点是可读可 ...

  10. 对数组进行malloc动态分配的一些总结

    笔者在处理程序奔溃问题的时候,遇到栈溢出的情况,栈溢出最常见的情况是:迭代调用和数组过大.数组占用占空间,所以改为了malloc方式放在堆上.想想,就想整理一下关于对多维数组的动态分配问题. 一,堆和 ...