Leetcode 97. Interleaving String
来源:互联网 发布:javaee和java的区别 编辑:程序博客网 时间:2024/05/11 03:30
97. Interleaving String
Total Accepted: 49560 Total Submissions: 219537 Difficulty: Hard
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.
解法一:
从前到后,取当前位置的s3中字符,如果匹配,则传递下一个位置进行匹配。但是大数据会超时。
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); char[] c3 = s3.toCharArray(); return helper(c1, c2, c3, 0, 0, 0); } private boolean helper(char[] c1, char[] c2, char[] c3, int p1, int p2, int p3){ if(p3==c3.length){ return p1==c1.length && p2==c2.length; } if(p1<c1.length && c3[p3]==c1[p1]){ if(helper(c1, c2, c3, p1+1, p2, p3+1)) return true; } if (p2<c2.length && c3[p3]==c2[p2]){ if(helper(c1, c2, c3, p1, p2+1, p3+1)) return true; } return false; }}
解法二:
dp。这题看似一维,其实是二维dp,因为len3=len1+len2。相当于z=x+y,有两个变量。用dp[i][j]表示s1的长度为i,s2的长度为j和s3的长度为i+j匹配。
初始化第一列和第一行之后,dp[i][j]= (dp[i-1][j] && c1[i-1]==c3[i-1+j]) || (dp[i][j-1] && c2[j-1]==c3[j-1+i]), 即跟上面和左边的位置有关。
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); char[] c3 = s3.toCharArray(); if(c3.length!=c1.length+c2.length) return false; boolean[][] dp = new boolean[c1.length+1][c2.length+1]; // row matches c1, col matches c2. dp[0][0]=true; for(int i=1; i<=c1.length; i++){ dp[i][0]= dp[i-1][0] && c1[i-1]==c3[i-1]; } for(int j=1; j<=c2.length; j++){ dp[0][j]= dp[0][j-1] && c2[j-1]==c3[j-1]; } for(int i=1; i<=c1.length; i++){ for(int j=1; j<=c2.length; j++){ dp[i][j]= (dp[i-1][j] && c1[i-1]==c3[i-1+j]) || (dp[i][j-1] && c2[j-1]==c3[j-1+i]); } } return dp[c1.length][c2.length]; }}
0 0
- LeetCode 97. Interleaving String
- [LeetCode]97.Interleaving String
- [Leetcode] 97. Interleaving String
- LeetCode --- 97. Interleaving String
- [leetcode] 97.Interleaving String
- [leetcode] 97.Interleaving String
- leetcode 97. Interleaving String
- Leetcode - 97.Interleaving String
- leetcode 97. Interleaving String
- LeetCode 97. Interleaving String
- LeetCode 97. Interleaving String
- Leetcode:97. Interleaving String
- Leetcode 97. Interleaving String
- [leetcode] 97. Interleaving String
- LeetCode-97.Interleaving String
- [LeetCode] 97. Interleaving String
- leetcode 97.Interleaving String
- 97. Interleaving String ,leetcode
- js判断一个对象数组里是否存在某个元素
- GCD的使用
- ftp服务怎么登陆
- 数据库之SQLite增删改查
- LeetCode 33. Search in Rotated Sorted Array(旋转数组搜索)
- Leetcode 97. Interleaving String
- Linux 系统的常用命令之 rm ,rm -rf , rm -f 以及rm 命令的其他参数命令
- FindFirstFile()函数
- 对Java反射机制的总结
- win7安装office2007失败
- Java中volatile关键字的含义
- APK动态加载框架DL库分析
- Markdown编辑管理工具(二)
- stosb, stosw, stosd 汇编指令