Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
For s1 = "aabcc"
, s2 = "dbbca"
- When s3 =
"aadbbcbcac"
, returntrue
. - When s3 =
"aadbbbaccc"
, returnfalse
.
动态规划,用一个二维数据记录:s1前i个字符,s2前j个字符,是不是s3前i + j个字符的interleave
状态转移:
dp[i - 1][j]为true,且s1的下一个字符和s3的下一个字符相等,或者dp[i][j - 1]为true,且s2的下一个字符和s3的下一个字符相等,则dp[i][j]为true,否则dp[i][j]为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 if(s1 == null && s2 == null && s3 == null) return true; if((s1 == null || s1.length() == 0) && s2.equals(s3)) return true; if((s2 == null || s2.length() == 0) && s1.equals(s3)) return true; int m = s1.length(); int n = s2.length(); int size3 = s3.length(); if(m + n != size3) return false; boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for(int i = 1; i <= n; i++) if(s2.charAt(i - 1) == s3.charAt(i - 1) && dp[0][i - 1]) dp[0][i] = true; else dp[0][i] = false; for(int i = 1; i <= m; i++) if(s1.charAt(i - 1) == s3.charAt(i - 1) && dp[i - 1][0]) dp[i][0] = true; else dp[i][0] = false; for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++){ if(dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) dp[i][j] = true; else if(dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)) dp[i][j] = true; else dp[i][j] = false; } } return dp[m][n]; } }
时间: 2024-11-10 13:36:29