Lintcode DP Interleaving String
18 Dec 2015###Task1 Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
Have you met this question in a real interview? Yes Example For s1 = “aabcc”, s2 = “dbbca”
When s3 = “aadbbcbcac”, return true. When s3 = “aadbbbaccc”, return false. Challenge O(n2) time or better
###Java ####DP
public class 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) {
// write your code here
if (s1.length() + s2.length() < s3.length()) {
return false;
}
int p = s1.length();
int q = s2.length();
boolean[][] dp = new boolean[p + 1][q + 1];
dp[0][0] = true;
for (int i = 1; i <= p; i++) {
if (dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1)) {
dp[i][0] = true;
}
}
for (int i = 1; i <= q; i++) {
if (dp[0][i - 1] && s2.charAt(i - 1) == s3.charAt(i - 1)) {
dp[0][i] = true;
}
}
for (int i = 1; i <= p; i++) {
for (int j = 1; j <= q; j++) {
if (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) {
dp[i][j] = true;
}
if (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
dp[i][j] = true;
}
}
}
return dp[p][q];
}
}
###Points
- DP
- string dp also initialized with dp[length + 1], since dp[0] also has meaning. dp[i] stands for previous i elements (arr[0] ~ arr[i - 1])