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
思路
可以遍历s1和s2所能构成的所有可能的interlaving string。
We start by taking the current character of the first string s1 and then appending all possible interleavings of the remaining portion of the first string s1 and the second string s2
and comparing each result formed with the required interleaved string s3. Similarly, we choose one character from the second string s2 and form all the interleavings with the
remaining portion of s2 and s1 to check if the required string s1 can be formed.
意思就是说先固定s1中的第一个字符,计算s1中剩下的部分和s2组成的所有可能的interleavings ,将s1添加到每个interleavings的前面,再和s3比较。相似的,固定s2中第第一个字符,然后计算s2剩下部分和s1所能构成的所有可能的interleavings。这里就用到了递归的方法。
代码
public class Solution {
public boolean is_Interleave(String s1,int i,String s2,int j,String res,String s3)
{
if(res.equals(s3) && i==s1.length() && j==s2.length())
return true;
boolean ans=false;
if(i<s1.length())
ans|=is_Interleave(s1,i+1,s2,j,res+s1.charAt(i),s3);
if(j<s2.length())
ans|=is_Interleave(s1,i,s2,j+1,res+s2.charAt(j),s3);
return ans;
}
public boolean isInterleave(String s1, String s2, String s3) {
return is_Interleave(s1,0,s2,0,"",s3);
}
}
当然这样可能会超时。现在介绍DP,DFS,BFS三种解法。
Using 2D Dynamic Programming
仔细观察 s1,s2。比如aab,bcc。我们去构造interleaving时无非就是先从一个字符串开始,然后选去另一个字符串中取或者在当前字符串之后取。比如说,一开始interleaving是空的,那么现在往里面加字符,第一个字符可能是a,也可能是b。如果加入了a,那么下个字符可能是a或者是c。就这样按一定路径去往interleaving里面加字符直到s1,s2全部取玩即构成了一个完整的的interleaving,和s3比较即可。
将s1, s2看成是一个二维平面地图
示例:s1="aa",s2="ab",s3="aaba"。标1的为可行。最终返回右下角。
0 a b
0 1 1 0
a 1 1 1
a 1 0 1
那么取s1中的字符就变成了向下走,取s2中的字符就变成了向右走。过程中要始终保持目前的interleaving是s3的prefix才行。
dp[i][j] -- implies if it is possible to obtain a substring of length (i+j+2) which is a prefix of s3 by some interleaving of prefixes of strings s1 and s2 having lengths (i+1) and (j+1) respectively.
递推公式:
如果索引位置(i, j)上的字符不匹配 s3 中的第k个字符,注意此时有 k=i+j+1。那么不用说了,直接置为false;
如果匹配并且是s1在i位置上的字符匹配的,那么要保证s1在i之前的部分和s2在j之前(包括j)的部分能构成s3在k之前的部分,否则如果是s2中索引j处的字符匹配的,那么要保证s1在i(包括i)之前的部分和s2在j之前的部分能构成s3在k之前的部分。
代码
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];
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
if (i == 0 && j == 0) {
dp[i][j] = true;
} else if (i == 0) {
dp[i][j] = dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);
} else if (j == 0) {
dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);
} else {
dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
}
}
}
return dp[s1.length()][s2.length()];
}
}
关于BFS和DFS的解释:https://leetcode.com/problems/interleaving-string/discuss/31904/Summary-of-solutions-BFS-DFS-DP