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

动态规划 

 1 public class Solution {
 2     public boolean isInterleave(String s1, String s2, String s3) {
 3         if (s3.length() != s1.length() + s2.length()) {
 4             return false;
 5         }
 6         boolean dp[][] = new boolean[s1.length() + 1][s2.length() + 1];
 7         for (int i = 0; i <= s1.length(); i++) {
 8             for (int j = 0; j <= s2.length(); j++) {
 9                 if (i == 0 && j == 0) {
10                     dp[i][j] = true;
11                 } else if (i == 0) {
12                     dp[i][j] = dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);
13                 } else if (j == 0) {
14                     dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);
15                 } else {
16                     dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
17                 }
18             }
19         }
20         return dp[s1.length()][s2.length()];
21     }
22 }
原文地址:https://www.cnblogs.com/zle1992/p/8533866.html