Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created September 8, 2013 03:32
Show Gist options
  • Save charlespunk/6481613 to your computer and use it in GitHub Desktop.
Save charlespunk/6481613 to your computer and use it in GitHub Desktop.
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.
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
// Start typing your Java solution below
// DO NOT write main() function
if(s1.length() + s2.length() != s3.length()) return false;
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
return isInterleave(s1, 0, s2, 0, s3, 0, dp);
}
private boolean isInterleave(String s1, int s1pos,
String s2, int s2pos, String s3, int s3pos, int[][] dp){
if(s3pos == s3.length()) return true;
if(dp[s1pos][s2pos] == 1) return false;
boolean r = false;
if(s1pos < s1.length() && s1.charAt(s1pos) == s3.charAt(s3pos)){
boolean next = isInterleave(s1, s1pos + 1, s2, s2pos, s3, s3pos + 1, dp);
if(!next) dp[s1pos + 1][s2pos] = 1;
r |= next;
}
if(!r && s2pos < s2.length() && s2.charAt(s2pos) == s3.charAt(s3pos)){
boolean next = isInterleave(s1, s1pos, s2, s2pos + 1, s3, s3pos + 1, dp);
if(!next) dp[s1pos][s2pos + 1] = 1;
r |= next;
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment