LeetCode刷题笔录Interleaving String
来源:互联网 发布:mac怎么玩免费的游戏 编辑:程序博客网 时间:2024/06/05 16:37
Given s1, s2, s3, find whethers3 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.
这题的第一反应就是动态规划,转移方程并不难想,主要是对于string长度和下标的关系要想清楚。
dp[i][j]表示用s1的前i个字符和s2的前j个字符能否interleave s3的前i+j个字符。s1的前i个字符是0到i-1;s2前j个字符是从0到j-1;s3前i+j个字符是从0到i+j-1。
dp[i][j]=true iff (dp[i-1][j]=true and s1[i-1]==s3[i+j-1], or dp[i][j-1]=true and s2[j-1]==s3[i+j-1])
base case稍微难想一点,i和j分别为0时,用s1或s2去匹配s3.
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { if(s3.length() != s1.length() + s2.length()) return false; boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; dp[0][0] = true; for(int i = 0; i < s1.length(); i++){ if(s1.charAt(i) == s3.charAt(i)) dp[i + 1][0] = true; } for(int j = 0; j < s2.length(); j++){ if(s2.charAt(j) == s3.charAt(j)) dp[0][j + 1] = true; } for(int i = 1; i <= s1.length(); i++){ for(int j = 1; j <= s2.length(); j++){ int c3 = s3.charAt(i + j - 1); if((dp[i - 1][j] && s1.charAt(i - 1) == c3) || (dp[i][j - 1] && s2.charAt(j - 1) == c3)) dp[i][j] = true; } } return dp[s1.length()][s2.length()]; }}
0 0
- LeetCode刷题笔录Interleaving String
- [leetcode刷题系列]Interleaving String
- LeetCode刷题笔录String to Integer (atoi)
- LeetCode刷题笔录Reverse Words in a 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
- [游戏技术]求生之路stripper:source游戏中创建模型
- 二分法求多项式根
- 为什么你的工作这么低效
- Leetcode Missing Ranges
- LeetCode: Jump Game
- LeetCode刷题笔录Interleaving String
- 2.关于QT中数据库操作,简单数据库连接操作,数据库的增删改查,QSqlTableModel和QTableView,事务操作,关于QItemDelegate 代理
- [BZOJ 2799]POI 2012 Salaries
- Leetcode One Edit Distance
- Leetcode Intersection of Two Linked Lists
- 近期总结
- {12月13日}“大数据讲座听后感”
- a5.java
- HDU2051(数制转换)