LeetCode 55 Interleaving String
来源:互联网 发布:淘宝内存卡骗局大全 编辑:程序博客网 时间:2024/05/23 02:04
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.
分析:
小妹妹说的没错,看见一个问题像贪心的时候,就该想想动规先,面试时不会出贪心这么直观的问题给你分析的。
设 mat[i][j] 表示s1从头开始长度为i子串和s2从头开始长度为j子串是否交叉成s3上从头开始长度(i+j)长度子串的结果,我们可以看出,这个问题跟最终问题是同质的,只是规模不同,这符合动态规划的标准。
接下来找状态转移方程:
mat[i][j] = mat[i-1][j] && (s1.charAt(i-1) == s3.charAt(i+j-1))
或者
mat[i][j] = mat[i][j-1] && (s2.chatAt(j-1) == s3.charAt(i+j-1))
接下来考虑初始化,
mat[0][0] 应该是true, 否则后面&&关系永远是false,另外初始化mat[i][0],mat[0][j].
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { if(s1 == null || s2 == null || s3 == null) return false; if(s3.length() != s1.length() + s2.length()) return false; boolean mat[][] = new boolean[s1.length()+1][s2.length()+1]; mat[0][0] = true; for(int i=1; i<s1.length()+1; i++){ if(s1.charAt(i-1) == s3.charAt(i-1) && mat[i-1][0]) mat[i][0] = true; else break; } for(int j=1; j<s2.length()+1; j++){ if(s2.charAt(j-1) == s3.charAt(j-1) && mat[0][j-1]) mat[0][j] = true; else break; } for(int i=1; i<s1.length()+1; i++) for(int j=1; j<s2.length()+1; j++){ if(s1.charAt(i-1) == s3.charAt(i+j-1) && mat[i-1][j]) mat[i][j] = true; if(s2.charAt(j-1) == s3.charAt(i+j-1) && mat[i][j-1]) mat[i][j] = true; } return mat[s1.length()][s2.length()]; }}
0 0
- LeetCode 55 Interleaving String
- LeetCode: Interleaving String
- LeetCode Interleaving String
- LeetCode: Interleaving String
- [Leetcode] Interleaving String
- [LeetCode] Interleaving String
- leetcode 68: Interleaving String
- [Leetcode] Interleaving String
- LeetCode - Interleaving String
- [LeetCode]Interleaving String
- LeetCode: Interleaving String
- Leetcode: Interleaving String
- [Leetcode]Interleaving String
- Leetcode: Interleaving String
- LeetCode:Interleaving String
- LeetCode-Interleaving String
- [leetcode] Interleaving String@DP
- LeetCode:Interleaving String
- HDU 3572 Task Schedule
- 【从开发者角度看测试】php+mysql+js登录注册系统
- scala学习笔记3(trait)
- 张小龙演讲全文:如何把产品做简单
- POJ--2709:Painter (贪心)
- LeetCode 55 Interleaving String
- 算法笔记--堆排序
- Phpstorm enviroment&Shortcut keys
- 【LeetCode】LRU Cache 解题报告
- Java 枚举常见7种用法
- Square Coins(dp-母函数)
- Oracle index】SQL语句利用函数索引注意点
- php学习准备
- 链表小程序-插入新节点