Monday, November 30, 2015

[leetcode]Interleaving String

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        if (s1.length()+s2.length() != s3.length()) return false;
        boolean lookup[] = new boolean[s2.length()+1];
        lookup[0] = true;
        for (int i = 1; i < lookup.length; i++){
            lookup[i] = lookup[i-1] && (s2.charAt(i-1) == s3.charAt(i-1));
        }
        for (int i = 1; i < s1.length()+1; i++){
            lookup[0] = lookup[0] && (s1.charAt(i-1) == s3.charAt(i-1));
            for (int j = 1; j < lookup.length; j++){
                lookup[j] = (lookup[j-1] && s2.charAt(j-1) == s3.charAt(j+i-1)) ||
                            (lookup[j] && s1.charAt(i-1) == s3.charAt(j+i-1));
            }
        }
        return lookup[lookup.length-1];
    }
}

No comments:

Post a Comment