码迷,mamicode.com
首页 > 其他好文 > 详细

Interleaving String

时间:2014-11-22 23:23:11      阅读:404      评论:0      收藏:0      [点我收藏+]

标签:io   ar   os   sp   java   for   on   代码   ad   

题目

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.

分析

  • 最直观的当然是递归了
  • 因为是两个变量,二维矩阵是少不了的
  • d[i][j]可以表达,当s1取前i个,s2取前j个,是否可以组成s3取前i+j个?
  • 编程上面有技巧,不能让d[s1.length][s2.length],这样index只能取到s1.length-1和s2.length-1
  • 推导公式,关键就在s1[i-1]==s3[i+j-1]这一句,因为是取s1的前i个,那最后一个就是s[i-1]了,这一点要严格按照d[i][j]的定义来

d[i][j] = (d[i-1][j]&&s1[i -1 ]==s3[i+j -1 ]) || (d[i][j-1]&&s2[j-1]==s3[i+j-1])

代码

package InterleaveString;

public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {

        if (s1.length() + s2.length() != s3.length()) {
            return false;
        }

        boolean[][] d = new boolean[s1.length()+1][s2.length()+1];
        d[0][0] = true;

        for (int i = 1; i <= s1.length(); i++) {
            if(s1.charAt(i-1) == s3.charAt(i-1)) {
                d[i][0] = true;
            } else {
                break;
            }
        }

        for (int j = 1; j <= s2.length(); j++) {
            if (s2.charAt(j-1) == s3.charAt(j-1)) {
                d[0][j] = true;
            } else {
                break;
            }
        }

        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                d[i][j] |= d[i - 1][j] && s1.charAt(i-1) == s3.charAt(i + j-1);
                d[i][j] |= d[i][j - 1] && s2.charAt(j-1) == s3.charAt(i + j-1);
            }
        }


        return d[s1.length()][s2.length()];
    }

}

Interleaving String

标签:io   ar   os   sp   java   for   on   代码   ad   

原文地址:http://my.oschina.net/zuoyc/blog/347676

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!