forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.cpp
53 lines (50 loc) · 1.49 KB
/
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
if (sentence.compare(0, searchWord.size(), searchWord) == 0) {
return 1;
}
searchWord = " " + searchWord;
auto p = KMP(sentence, searchWord);
if (p == -1) {
return -1;
}
return 1 + accumulate(cbegin(sentence), cbegin(sentence) + p + 1, 0,
[](const auto& a, const auto& b) {
return a + (b == ' ');
});
}
private:
int KMP(const string& text, const string& pattern) {
const vector<int> prefix = getPrefix(pattern);
int j = -1;
for (int i = 0; i < text.length(); ++i) {
while (j > -1 && pattern[j + 1] != text[i]) {
j = prefix[j];
}
if (pattern[j + 1] == text[i]) {
++j;
}
if (j == pattern.length() - 1) {
return i - j;
}
}
return -1;
}
vector<int> getPrefix(const string& pattern) {
vector<int> prefix(pattern.length(), -1);
int j = -1;
for (int i = 1; i < pattern.length(); ++i) {
while (j > -1 && pattern[j + 1] != pattern[i]) {
j = prefix[j];
}
if (pattern[j + 1] == pattern[i]) {
++j;
}
prefix[i] = j;
}
return prefix;
}
};