-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.cpp
More file actions
79 lines (70 loc) · 1.47 KB
/
string.cpp
File metadata and controls
79 lines (70 loc) · 1.47 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
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
74
75
76
77
78
79
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// KMP Failure Function
vector<int> getPi(string p) {
int m = p.size(), j = 0;
vector<int> pi(m, 0);
for (int i = 1; i < m; i++) {
while (j > 0 && p[i] != p[j])
j = pi[j - 1];
if (p[i] == p[j])
pi[i] = ++j;
}
return pi;
}
// KMP Search
vector<int> kmp(string s, string p) {
vector<int> ans;
auto pi = getPi(p);
int n = s.size(), m = p.size(), j = 0;
for (int i = 0; i < n; i++) {
while (j > 0 && s[i] != p[j])
j = pi[j - 1];
if (s[i] == p[j]) {
if (j == m - 1) {
ans.push_back(i - m + 1);
j = pi[j];
} else
j++;
}
}
return ans;
}
// Trie Node
struct TrieNode {
TrieNode *children[26];
bool isEnd;
TrieNode() {
for (int i = 0; i < 26; i++)
children[i] = nullptr;
isEnd = false;
}
~TrieNode() {
for (int i = 0; i < 26; i++)
if (children[i])
delete children[i];
}
};
// Trie Insert/Search
void insert(TrieNode *root, string key) {
TrieNode *curr = root;
for (char c : key) {
int idx = c - 'a';
if (!curr->children[idx])
curr->children[idx] = new TrieNode();
curr = curr->children[idx];
}
curr->isEnd = true;
}
bool search(TrieNode *root, string key) {
TrieNode *curr = root;
for (char c : key) {
int idx = c - 'a';
if (!curr->children[idx])
return false;
curr = curr->children[idx];
}
return curr != nullptr && curr->isEnd;
}