leetcode--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.

rewrite the code

public class Solution {
    /**
	 * Standard dynamic programming methodology.
	 * @param s1 -String 
	 * @param s2 -String
	 * @param s3 -String which is to be checked
	 * @return true when s3 is formed by the interleaving of s1 and s2, false, otherwise.
	 * @author Averill Zheng
	 * @version 2014-06-27
	 * @since JDK 1.7 
	 */
	public boolean isInterleave(String s1, String s2, String s3) {
		if(s1.length() == 0)
			return s2.equals(s3);
		if(s2.length() == 0)
			return s1.equals(s3);
		if(s1.length() + s2.length() != s3.length())
			return false;
		
		boolean[][] check = new boolean[s1.length() + 1][s2.length() + 1];
		check[0][0] = true;
		for(int i = 1; i < s1.length() + 1; ++i)
			check[i][0] = check[i - 1][0] && (s1.charAt(i - 1) == s3.charAt(i - 1));
		for(int i = 1; i < s2.length() + 1; ++i)
			check[0][i] = check[0][i - 1] && (s2.charAt(i - 1) == s3.charAt(i - 1));
		for(int i = 1; i < s1.length() + 1; ++i) {
			for(int j = 1; j < s2.length() + 1; ++j) {
				check[i][j] = (check[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1))
							||(check[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1));
			}
		}
		return check[s1.length()][s2.length()];  
    }
}

  

method: dynamical programming...

 

 1 public class Solution {
 2     public boolean isInterleave(String s1, String s2, String s3) {
 3         int len1 = s1.length(), len2= s2.length(), len3 = s3.length();
 4         if(len1 == 0 || len2 == 0)
 5             return s3.equals(s1) || s3.equals(s2);
 6         if(len3 != len1 + len2)
 7             return false;
 8         int[][] paths = new int[len1 + 1][len2 + 1];
 9         paths[0][0] = 1;
10         for(int i = 1; i < len2 + 1; ++i)
11             paths[0][i] = (s2.charAt(i - 1) == s3.charAt(i - 1)) ? 1 : 0;
12         for(int i = 1; i < len1 + 1; ++i)
13             paths[i][0] = (s1.charAt(i - 1) == s3.charAt(i - 1)) ? 1 : 0;
14         for(int i = 1; i < len1 + 1; ++i){
15             for(int j = 1; j < len2 + 1; ++j){
16                 if(paths[i][j - 1] == 1 && s3.charAt(i + j - 1) == s2.charAt(j - 1))
17                     paths[i][j] = 1;
18                 else if(paths[i - 1][j] == 1 && s3.charAt(i + j - 1) == s1.charAt(i - 1))
19                     paths[i][j] = 1;
20                 else
21                     paths[i][j] = 0;
22             }            
23         }         
24         return (paths[len1][len2] == 1)? true : false;        
25     }
26 }

 

posted @ 2014-02-01 04:41  Averill Zheng  阅读(150)  评论(0编辑  收藏  举报