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

[LeetCode]Interleaving String

时间:2014-11-24 10:16:50      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

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.

二维动态规划 参考LeetCode题解 戴方勤 

public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        if(s1.length()==0&&s2.length()==0&&s3.length()==0) return true;
        if(s1.length()+s2.length()!=s3.length()) return false;
        boolean f[][] = new boolean[s1.length()+1][s2.length()+1];
        for(int i=0;i<s1.length();i++){
        	f[i+1][0] = (s1.charAt(i)==s3.charAt(i));
        }
        
        for(int i=0;i<s2.length();i++){
        	f[0][i+1] = (s2.charAt(i)==s3.charAt(i));
        }
        
        for(int i=0;i<s1.length();i++){
        	for(int j=0;j<s2.length();j++){
        		f[i+1][j+1] = ((s1.charAt(i)==s3.charAt(i+j+1))&&f[i][j+1])||
        				((s2.charAt(j)==s3.charAt(i+j+1))&&f[i+1][j]);
        	}
        }
        return f[s1.length()][s2.length()];
    }
}





[LeetCode]Interleaving String

标签:java   leetcode   

原文地址:http://blog.csdn.net/guorudi/article/details/41414801

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