Java implementation LeetCode 97 cross strings

97. staggered string

Given three strings s1, s2, s3, s3 verify interleaved by s1 and s2 thereof.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

class Solution {
   public boolean isInterleave(String s1, String s2, String s3) {
        if((s1.length() + s2.length()) != s3.length()) return false;

        boolean[][] dp = new boolean[s2.length() + 1][s1.length() + 1];

        dp[0][0] = true;
        for(int i = 1; i <= s1.length(); i++){
            dp[0][i] = dp[0][i-1]&&s1.charAt(i-1)==s3.charAt(i-1)? true : false;
        }

        for(int i = 1; i <= s2.length(); i++){
            dp[i][0] = dp[i-1][0]&&s2.charAt(i-1)==s3.charAt(i-1)? true : false;
        }

        for(int i = 1; i < dp.length; i++){
            for(int j = 1; j < dp[0].length; j++){
                dp[i][j] = (dp[i][j-1] && s1.charAt(j-1) == s3.charAt(i + j-1)) || (dp[i - 1][j] && s2.charAt(i-1) == s3.charAt(i + j-1));
            }
        }
        return dp[s2.length()][s1.length()];
    }
}
Released 1214 original articles · won praise 10000 + · Views 650,000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104374282