題目
給出三個(gè)字符串:s1狼渊、s2女器、s3,判斷s3是否由s1和s2交叉構(gòu)成
樣例
比如 s1 = "aabcc" s2 = "dbbca"
- 當(dāng) s3 = "aadbbcbcac"放接,返回 true.
- 當(dāng) s3 = "aadbbbaccc"究飞, 返回 false.
分析
動(dòng)態(tài)規(guī)劃問(wèn)題
dp[i][j]:表示前i個(gè)和前j 個(gè)是否構(gòu)成
顯然當(dāng)?shù)趕3的i+j個(gè)字符,就兩種可能放坏,一個(gè)等于s1,一個(gè)等于s2咙咽。
代碼
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.length() + s2.length() != s3.length()) {
return false;
}
boolean [][] interleaved = new boolean[s1.length() + 1][s2.length() + 1];
interleaved[0][0] = true;
for (int i = 1; i <= s1.length(); i++) {
if(s3.charAt(i - 1) == s1.charAt(i - 1) && interleaved[i - 1][0])
interleaved[i][0] = true;
}
for (int j = 1; j <= s2.length(); j++) {
if(s3.charAt(j - 1) == s2.charAt(j - 1) && interleaved[0][j - 1])
interleaved[0][j] = true;
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if(((s3.charAt(i + j - 1) == s1.charAt(i - 1) && interleaved[i - 1][j]))
|| ((s3.charAt(i + j - 1)) == s2.charAt(j - 1) && interleaved[i][j - 1]))
interleaved[i][j] = true;
}
}
return interleaved[s1.length()][s2.length()];
}
}