-
Notifications
You must be signed in to change notification settings - Fork 3
/
3043.cpp
54 lines (52 loc) · 1.27 KB
/
3043.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
class TrieNode {
public:
vector<TrieNode*> children;
TrieNode() {
children.resize(10, nullptr);
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void insert(string& s) {
int n = s.size();
TrieNode* cur = root;
for (int i = 0; i < n; ++i) {
if (!cur->children[s[i] - '0']) {
cur->children[s[i] - '0'] = new TrieNode();
}
cur = cur->children[s[i] - '0'];
}
}
int maxDepth(string& s) {
int n = s.size();
TrieNode* cur = root;
int depth = 0;
for (int i = 0; i < n; ++i) {
if (!cur->children[s[i] - '0']) break;
cur = cur->children[s[i] - '0'];
depth = i + 1;
}
return depth;
}
};
class Solution {
public:
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
Trie* trie = new Trie();
for (auto& num : arr1) {
string s = to_string(num);
trie->insert(s);
}
int maxDepth = 0;
for (auto& num : arr2) {
string s = to_string(num);
int depth = trie->maxDepth(s);
maxDepth = max(depth, maxDepth);
}
return maxDepth;
}
};