leetcode Interleaving String
来源:互联网 发布:网络媒介类型主要有 编辑:程序博客网 时间:2024/06/11 08: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
遇到字符串问题一定要优先考虑dp,我们可以用一个二维数组dp[I][j],代表取s1的前I位和s2的前j位,与s3的前I+j位进行比较,那么递推关系是什么呢?
如果第s3[i+j]=s1[I],那么我们需要判断s3[I-1][j]是否为true,即前I+j-1位与s1取I-1位、s2取j位是否相等,如果相等,则s3[I][j]才能为true,同理j,代码:
public boolean isInterleave(String s1, String s2, String s3) { int m=s1.length(),n=s2.length(); if(m+n!=s3.length())return false; boolean[][] res=new boolean[m+1][n+1]; res[0][0]=true; for(int j=1;j<=n;j++){ if(s2.charAt(j-1)==s3.charAt(j-1)&&res[0][j-1]) res[0][j]=true; } for(int i=1;i<=m;i++){ if(s1.charAt(i-1)==s3.charAt(i-1)&&res[i-1][0]) res[i][0]=true; } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ int k=i+j-1; if((s3.charAt(k)==s1.charAt(i-1)&&res[i-1][j])||(s3.charAt(k)==s2.charAt(j-1)&&res[i][j-1])) res[i][j]=true; } } return res[m][n];}
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
- Zabbix监控之邮件发送失败-smtp-server: "550 User has no permission"
- LeetCode136—Single Number
- JavaEE项目实战(OA系统)之二_数据库设计
- Window批处理命令教程
- 我要改变!我要改变!我要改变!
- leetcode Interleaving String
- 【mongoDB 操作】--update, remove, $set, $push
- 使用libcurl提示 LNK2001的错误
- Android Studio 百度地图开发准备工作以及问题分析
- limit分页语句用法
- 怎么共享打印机
- 0xa0是什么意思
- 下载文件并打开
- 第2周 项目0 宣告“主权”