两个字符串交叉得到的字符串 Interleaving String @LeetCode

同 《DP33 两个字符串交叉得到的字符串 Find if a string is interleaved of two other strings @geeksforgeeks》


package Level5;

/**
Interleaving String 

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.

 */
public class S97 {

	public static void main(String[] args) {

	}

	public boolean isInterleave(String s1, String s2, String s3) {
		int L1 = s1.length();       // Find lengths of the two strings  
        int L2 = s2.length();  
        int L = s3.length();  
          
        // Let us create a 2D table to store solutions of  
        // subproblems.  isIL[i][j] will be true if s[0..i+j-1]  
        // is an interleaving of s1[0..i-1] and s2[0..j-1].  
        boolean[][] isIL = new boolean[L1+1][L2+1];  
          
        // C can be an interleaving of A and B only of sum  
        // of lengths of A & B is equal to length of C.  
        if(L1+L2 != L){  
            return false;  
        }  
          
        for(int l1=0; l1<=L1; l1++){  
            for(int l2=0; l2<=L2; l2++){  
                // two empty strings have an empty string as interleaving  
                if(l1==0 && l2==0){  
                    isIL[l1][l2] = true;  
                }  
                // A is empty  
                else if(l1==0 && s2.charAt(l2-1)==s3.charAt(l2-1)){  
                    isIL[l1][l2] = isIL[l1][l2-1];  
                }  
                // B is empty  
                else if(l2==0 && s1.charAt(l1-1)==s3.charAt(l1-1)){  
                    isIL[l1][l2] = isIL[l1-1][l2];  
                }  
                  
                if(l1!=0 && l2!=0){  
                    // Current character of C matches with current character of A,  
                    // but doesn't match with current character of B  
                    if(s3.charAt(l1+l2-1)==s1.charAt(l1-1) && s3.charAt(l1+l2-1)!=s2.charAt(l2-1)){  
                        isIL[l1][l2] = isIL[l1-1][l2];  
                    }  
                    // Current character of C matches with current character of B,  
                    // but doesn't match with current character of A  
                    else if(s3.charAt(l1+l2-1)==s2.charAt(l2-1) && s3.charAt(l1+l2-1)!=s1.charAt(l1-1)){  
                        isIL[l1][l2] = isIL[l1][l2-1];  
                    }  
                    // Current character of C matches with that of both A and B  
                    else if(s3.charAt(l1+l2-1)==s1.charAt(l1-1) && s3.charAt(l1+l2-1)==s2.charAt(l2-1)){  
                        isIL[l1][l2] = isIL[l1-1][l2] || isIL[l1][l2-1];  
                    }  
                }  
            }  
        }  
          
        return isIL[L1][L2];  
	}

}


你可能感兴趣的:(两个字符串交叉得到的字符串 Interleaving String @LeetCode)