标签:
Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
For s1 = "aabcc"
, s2 = "dbbca"
"aadbbcbcac"
, return true
."aadbbbaccc"
, return false
.
For this problem, if we think about the problem in the combination way then we have l1 = s1.length(); l2 = s2.length(); l3 = s3.length(); We have O(2^(l3)) ways to chose appropriate char to the certain slot then we can construct the s3. Due to the requirement of the problem we have want to use additional memory to store the repeated calculated result which could be used to solve larger problem with trivial manipulation directly. So this problem, we could use two dimentional array to store if the first i chars from s1 and first j chars from s2 could be used to construct the first i+j chars of s3. The result will be boolean true or false.
public class Solution { /** * Determine whether s3 is formed by interleaving of s1 and s2. * @param s1, s2, s3: As description. * @return: true or false. */ public boolean isInterleave(String s1, String s2, String s3) { // write your code here int l1 = s1.length(); int l2 = s2.length(); //edge case when the l1+l2 does not equals to the s3 length return false if (l1 + l2 != s3.length()) { return false; } //Define the state that boolean isInterleave[i][j] stand for i-length s1 //and j-length s2 could be combined to construct a i+j-length word s3 boolean[][] isInterleave = new boolean[l1+1][l2+1]; isInterleave[0][0] = true; //initialize all situations that use s1 to construct s3 for (int i = 1; i <= l1; i++) { isInterleave[i][0] = (s1.charAt(i-1) == s3.charAt(i-1)) && isInterleave[i-1][0]; } //initialize all situations that use s2 to construct s3 for (int i = 1; i <=l2; i++) { isInterleave[0][i] = (s2.charAt(i-1) == s3.charAt(i-1)) && isInterleave[0][i-1]; } for(int i = 1; i <= l1; i++) { for(int j = 1; j <= l2; j++) { isInterleave[i][j] = (isInterleave[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1)) || ((isInterleave[i][j-1]) && s2.charAt(j-1) == s3.charAt(i+j-1)); } } return isInterleave[l1][l2]; } }
标签:
原文地址:http://www.cnblogs.com/ly91417/p/5774904.html