`
hcx2013
  • 浏览: 88791 次
社区版块
存档分类
最新评论

Interleaving String

 
阅读更多

Given s1s2s3, 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) {
        if (s1.length()+s2.length() != s3.length()) {
        	return false;
        }
        boolean[][] res = new boolean[s1.length()+1][s2.length()+1];
        res[0][0] = true;
        for (int i = 1; i <= s1.length() && s1.charAt(i-1) == s3.charAt(i-1); i++) {
			res[i][0] = true;
		}
        for (int i = 1; i <= s2.length() && s2.charAt(i-1) == s3.charAt(i-1); i++) {
			res[0][i] = true;
		}
        for (int i = 1; i <= s1.length(); i++) {
			for (int j = 1; j <= s2.length(); j++) {
				char charAt = s3.charAt(i+j-1);
				if (s1.charAt(i-1)==charAt && res[i-1][j]) {
					res[i][j] = true;
				}
				if (s2.charAt(j-1)==charAt && res[i][j-1]) {
					res[i][j] = true;
				}
			}
		}
        return res[s1.length()][s2.length()];
    }
}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics