forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
56 lines (55 loc) · 1.58 KB
/
Solution.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
class Solution {
public:
bool patternMatching(string pattern, string value) {
int n = value.size();
int cnt[2]{};
for (char c : pattern) {
cnt[c - 'a']++;
}
if (cnt[0] == 0) {
return n % cnt[1] == 0 && repeat(value.substr(0, n / cnt[1]), cnt[1]) == value;
}
if (cnt[1] == 0) {
return n % cnt[0] == 0 && repeat(value.substr(0, n / cnt[0]), cnt[0]) == value;
}
auto check = [&](int la, int lb) {
int i = 0;
string a, b;
for (char c : pattern) {
if (c == 'a') {
if (!a.empty() && a != value.substr(i, la)) {
return false;
}
a = value.substr(i, la);
i += la;
} else {
if (!b.empty() && b != value.substr(i, lb)) {
return false;
}
b = value.substr(i, lb);
i += lb;
}
}
return a != b;
};
for (int la = 0; la <= n; ++la) {
if (la * cnt[0] > n) {
break;
}
if ((n - la * cnt[0]) % cnt[1] == 0) {
int lb = (n - la * cnt[0]) / cnt[1];
if (check(la, lb)) {
return true;
}
}
}
return false;
}
string repeat(string s, int n) {
string ans;
while (n--) {
ans += s;
}
return ans;
}
};