Leetcode 97. Interleaving String
2016-05-19 10:04
330 查看
97. Interleaving String
Total Accepted: 49560 TotalSubmissions: 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];
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解