Interleaving String
Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
Example
For s1 = "aabcc", s2 = "dbbca"
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
Challenge
time or better
Think
- Two sequence DP, 2-D memorized boolean array
memo[i][j]means fromword1(1,i)andword2(1,j)can form theword3(1, i+j)- Initial the case
memo[0][j]andmemo[i][0]is false andmemo[0][0]should be true. - Pass through
ifrom0toword1.lengthandjfrom0toword2.length, check ifword3[i+j-1]== word2[j-1]orword3[i+j-1]== word1[i-1] - We also have to make sure when
word3[i+j-1]== word2[j-1], thememo[i][j-1]should be true orword3[i+j-1]== word1[i-1], thememo[i-1][j]should be true - Get the
memo[len1][len2]as the final boolean result
Solution
/**
* Determine whether s3 is formed by interleaving of s1 and s2.
* @param s1, s2, s3: As description.
* @return: true or false.
*/
public boolean isInterleave(String s1, String s2, String s3) {
if(s1 == null || s2 == null)
return false;
if(s1.length() + s2.length() != s3.length())
return false;
boolean[][] memo = 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)
memo[i][j] = true;
else{
if(i > 0 && s1.charAt(i - 1) == s3.charAt(i + j - 1))
memo[i][j] = memo[i - 1][j];
if(j > 0 &&s2.charAt(j - 1) == s3.charAt(i + j - 1))
memo[i][j] |= memo[i][j - 1];
}
}
}
return memo[s1.length()][s2.length()];
}