-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathpartition-string.cpp
More file actions
52 lines (46 loc) · 1.03 KB
/
partition-string.cpp
File metadata and controls
52 lines (46 loc) · 1.03 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
// Time: O(n)
// Space: O(t)
// simulation, trie
class Solution {
public:
vector<string> partitionString(string s) {
vector<string> result;
Trie trie;
string curr;
for (const auto& c : s) {
curr.push_back(c);
trie.add(c);
if (trie.curr()) {
continue;
}
result.emplace_back(move(curr));
}
return result;
}
private:
class Trie {
public:
Trie() {
new_node();
}
void add(int c) {
const auto& x = c - 'a';
if (nodes_[curr_][x] == -1) {
nodes_[curr_][x] = new_node();
curr_ = 0;
return;
}
curr_ = nodes_[curr_][x];
}
int curr() const {
return curr_;
}
private:
int new_node() {
nodes_.emplace_back(26, -1);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
int curr_ = 0;
};
};