97 - Interleaving String
作者:互联网
Problem
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
Code
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int l1 = s1.length();
int l2 = s2.length();
int l3 = s3.length();
if (l1 == 0 && l2 == 0 && l3 == 0) {
return true;
}
if (l1 + l2 != l3) {
return false;
}
if (l1 == 0) {
return s3.compareTo(s2) == 0;
}
boolean[][] dp = new boolean[l3 + 1][l1 + 1];
dp[0][0] = true;
for (int i = 1; i <= l3; ++i) {
for (int j = 0; j <= l1 && j <= i; ++j) {
if ((j > 0 && dp[i - 1][j - 1] && s3.charAt(i - 1) == s1.charAt(j - 1))
|| (i - j >= 1 && i - j <= l2 && dp[i - 1][j] && s3.charAt(i - 1) == s2.charAt(i - j - 1))) {
//System.out.println(i + " " + j);
dp[i][j] = true;
}
}
}
return dp[l3][l1];
}
}
Link: https://leetcode.com/problems/interleaving-string/
标签:String,s3,s2,Interleaving,int,&&,l1,s1,97 来源: https://blog.csdn.net/LvShuiLanTian/article/details/95477677