LeetCode-Interleaving String
来源:互联网 发布:淘宝店突然没生意了 编辑:程序博客网 时间:2024/06/14 22:33
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.
又是一个关于字符串的动态规划题,Distinct Subsequences、Edit Distance都差不多,肯定回溯法是可以解出来的,但是肯定时间复杂度比较高。这时候想起来动态规划算法。分析基本跟上述两个问题的方式是一样的。
还是看住最后一个字符s1[j], s2[i]与s3[i+j-1]之间的关系,代码见下:
public boolean isInterleave(String s1, String s2, String s3) { if (s1.length() + s2.length() != s3.length()) return false; boolean[][] dp = new boolean[s2.length()+1][s1.length()+1]; dp[0][0] = true; for (int i = 1; i < dp[0].length; i++) { dp[0][i] = s1.charAt(i-1) == s3.charAt(i-1) && dp[0][i-1]; } for (int i = 1; i < dp.length; i++) { dp[i][0] = s2.charAt(i-1) == s3.charAt(i-1) && dp[i-1][0]; } for (int i = 1; i < dp.length; i++) { for (int j = 1; j < dp[i].length; j++) { dp[i][j] = (s3.charAt(i+j-1) == s1.charAt(j-1) && dp[i][j-1]) || (s3.charAt(i+j-1) == s2.charAt(i-1) && dp[i-1][j]); } } return dp[s2.length()][s1.length()]; }
0 0
- 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
- LeetCode - Interleaving String
- 程序员如何高效阅读
- 有选择性的安装文件
- 集合-List实现类、泛型
- LightOJ(1422)——Halloween Costumes
- ActionBar的完整介绍
- LeetCode-Interleaving String
- Set类、Collections
- HDU 1024 Max Sum Plus Plus(最大M子段和)
- 安卓国际化,应用内切换语言
- 微信支付-----统一下单action
- 作业《IOS_C语言》进制,C数据类型,常量类型,运算符,表达式,格式化输入输出
- 求子序列的和的最大值
- Qt编译安装方法详解:包含数据库驱动的编译安装方法
- 集成VIM强大的代码编辑器(一)