-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathInterleavingString.cpp
49 lines (37 loc) · 1.17 KB
/
InterleavingString.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
// Problem: https://leetcode.com/problems/interleaving-string/
#include <string>
#include <unordered_map>
using namespace std;
class InterleavingString {
public:
bool isInterleave(string s1, string s2, string s3) {
return isInterleaveInt(s3, s1, s2);
}
bool isInterleaveInt(string s1, string s2, string s3) {
if (s1.size() != (s2.size() + s3.size())) return false;
// S1.size = S2.size + S3.size
// All characters checked.
if (s1.size() == 0) return true;
// One string empty.
if (s2.size() == 0) return s1 == s3;
if (s3.size() == 0) return s1 == s2;
const string key = ToString(s1.size(), s2.size(), s3.size());
if (memo_map.find(key) != memo_map.end()) return memo_map[key];
bool found = false;
// Explore one route.
if (s1.at(0) == s2.at(0)) {
found = isInterleaveInt(s1.substr(1), s2.substr(1), s3);
}
// Explore other route.
if (s1.at(0) == s3.at(0)) {
found = found || isInterleaveInt(s1.substr(1), s2, s3.substr(1));
}
memo_map[key] = found;
return found;
}
private:
unordered_map<string, bool> memo_map;
string ToString(int i, int j, int k) {
return std::to_string(i) + "," + std::to_string(j) + "," + std::to_string(k);
}
};