-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
43 lines (37 loc) · 1.06 KB
/
Copy pathsolution.cpp
File metadata and controls
43 lines (37 loc) · 1.06 KB
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
#include <string>
#include <vector>
bool canShiftString(const std::string& a, const std::string& b) {
if (a.size() != b.size()) {
return false;
}
if (a.empty()) {
return true;
}
const std::string text = a + a;
const std::string& pattern = b;
std::vector<int> prefix(pattern.size(), 0);
for (std::size_t i = 1, j = 0; i < pattern.size(); ++i) {
while (j > 0 && pattern[i] != pattern[j]) {
j = static_cast<std::size_t>(prefix[j - 1]);
}
if (pattern[i] == pattern[j]) {
++j;
}
prefix[i] = static_cast<int>(j);
}
for (std::size_t i = 0, j = 0; i < text.size(); ++i) {
while (j > 0 && text[i] != pattern[j]) {
j = static_cast<std::size_t>(prefix[j - 1]);
}
if (text[i] == pattern[j]) {
++j;
}
if (j == pattern.size()) {
if (i + 1 - j < a.size()) {
return true;
}
j = static_cast<std::size_t>(prefix[j - 1]);
}
}
return false;
}