LeetCode 87. Scramble String
参考链接:[1]https://blog.youkuaiyun.com/makuiyu/article/details/44926439
[2]http://www.cnblogs.com/grandyang/p/4318500.html
Solution1:
递归
class Solution {
public:
bool isScramble(string s1, string s2) {
return isScramble(s1, 0, s1.size() - 1, s2, 0, s2.size() - 1);
}
private:
bool isScramble(string s1, int a1, int b1, string s2, int a2, int b2) {
if (b1 - a1 != b2 - a2)
return false;
if (a1 == b1)
return s1[a1] == s2[a2];
// 剪枝,如果子串中的字符不同,则必然不是Scramble String,不用再进行分割处理了
int cnt[256] = {0};
for(int i = a1; i <= b1; ++ i)
++cnt[s1[i]];
for(int i = a2; i <= b2; ++ i)
--cnt[s2[i]];
for(int i = 0; i < 256 ;++ i)
if (cnt[i] != 0)
return false;
for (int i = a1; i < b1; ++ i) {
if (isScramble(s1, a1, i, s2, a2, a2 + i - a1) &&
isScramble(s1, i + 1, b1, s2, b2 - (b1 - i - 1), b2))
return true;
if (isScramble(s1, a1, i, s2, b2 - (i - a1), b2) &&
isScramble(s1, i + 1, b1, s2, a2, a2 + b1 - i - 1))
return true;
}
return false;
}
};
Solution2:
DP
class Solution {
public:
bool isScramble(string s1, string s2) {
if (s1.size() != s2.size()) return false;
if (s1 == s2) return true;
int n = s1.size();
vector<vector<vector<bool> > > dp (n, vector<vector<bool> >(n, vector<bool>(n + 1, false)));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
dp[i][j][1] = s1[i] == s2[j];
}
}
for (int len = 2; len <= n; ++len) {
for (int i = 0; i <= n - len; ++i) {
for (int j = 0; j <= n - len; ++j) {
for (int k = 1; k < len; ++k) {
if ((dp[i][j][k] && dp[i + k][j + k][len - k]) || (dp[i + k][j][len - k] && dp[i][j + len - k][k])) {
dp[i][j][len] = true;
}
}
}
}
}
return dp[0][0][n];
}
};