-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathphone-number-prefix.cpp
66 lines (60 loc) · 1.46 KB
/
phone-number-prefix.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
57
58
59
60
61
62
63
64
65
66
// Time: O(l * nlogn)
// Space: O(1)
// sort
class Solution {
public:
bool phonePrefix(vector<string>& numbers) {
sort(begin(numbers), end(numbers));
for (int i = 0; i + 1 < size(numbers); ++i) {
if (numbers[i + 1].starts_with(numbers[i])) {
return false;
}
}
return true;
}
};
// Time: O(n * l)
// Space: O(t)
// trie
class Solution2 {
private:
class Trie {
public:
Trie() {
new_node();
}
bool add(const string& s) {
bool made = false;
int curr = 0;
for (int i = 0; i < size(s); ++i) {
const int x = s[i] - '0';
if (nodes_[curr][x] == -1) {
nodes_[curr][x] = new_node();
made = true;
} else if (nodes_[nodes_[curr][x]].back() == 1) {
return false;
}
curr = nodes_[curr][x];
}
nodes_[curr].back() = 1;
return made;
}
private:
int new_node() {
nodes_.emplace_back(11, -1);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
vector<int> cnts_;
};
public:
bool phonePrefix(vector<string>& numbers) {
Trie trie;
for (const auto& x : numbers) {
if (!trie.add(x)) {
return false;
}
}
return true;
}
};