[LeetCode]Interleaving String

动规

public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        int length1 = s1.length();
        int length2 = s2.length();
        if (s3.length() != length1 + length2){
            return false;
        }
        int[][] record = new int[length1 + 1][length2 + 1];
        for (int r = 0; r <= length1; r++) {
            for (int c = 0; c <= length2; c++) {
                if (r == 0 && c == 0) {
                    record[r][c] = 1;
                    continue;
                }
                if (c != 0 && record[r][c - 1] != 0) {
                    record[r][c] = s3.charAt(record[r][c - 1] - 1) == s2.charAt(c - 1) ? record[r][c - 1] + 1 : 0;
                }
                if (r != 0 && record[r - 1][c] != 0) {
                    int tmp = s3.charAt(record[r - 1][c] - 1) == s1.charAt(r - 1) ? record[r - 1][c] + 1 : 0;
                    record[r][c] = Math.max(tmp, record[r][c]);
                }
            }
        }
        return record[length1][length2] - 1 == s3.length();
    }
}

 

posted @ 2015-12-02 04:38  Weizheng_Love_Coding  阅读(102)  评论(0编辑  收藏  举报