forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
73 lines (56 loc) · 1.79 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/// Source : https://leetcode.com/problems/scramble-string/description/
/// Author : liuyubobobo
/// Time : 2018-04-23
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
/// Memory Search
/// Time Complexity: O(26^n)
/// Space Complexity: O(n^2)
class Solution {
public:
bool isScramble(string s1, string s2) {
if(s1.size() != s2.size())
return false;
unordered_map<string, bool> memo;
return isScramble(s1, s2, memo);
}
private:
bool isScramble(string s1, string s2, unordered_map<string, bool>& memo) {
string key = s1 + s2;
if(memo.find(key) != memo.end())
return memo[key];
if(s1 == s2)
return memo[key] = true;
unordered_map<char, int> freq;
for(char c: s1)
freq[c] += 1;
for(char c: s2)
if(freq.find(c) == freq.end())
return memo[key] = false;
else{
freq[c] -= 1;
if(freq[c] == 0)
freq.erase(c);
}
for(int i = 1 ; i <= s1.size() - 1 ; i ++){
if(isScramble(s1.substr(0, i), s2.substr(0, i))
&& isScramble(s1.substr(i), s2.substr(i)))
return memo[key] = true;
if(isScramble(s1.substr(0, i), s2.substr(s2.size() - i))
&& isScramble(s1.substr(i), s2.substr(0, s2.size() - i)))
return memo[key] = true;
}
return memo[key] = false;
}
};
void print_bool(bool res){
cout << (res ? "true" : "false") << endl;
}
int main() {
print_bool(Solution().isScramble("great", "rgeat"));
print_bool(Solution().isScramble("abcde", "caebd"));
print_bool(Solution().isScramble("abcdefghijklmn", "efghijklmncadb"));
return 0;
}