题目地址:
https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/description/
给定两个数组 a a a和 b b b,各自取一个数,求它们的最长公共前缀的长度(就是看成字符串后求),题目保证只含非负整数,且没有前导 0 0 0。问最长的最长公共前缀的长度。
思路是Trie。先将 a a a里的所有数插进Trie,然后遍历 b b b求最长公共前缀长度。代码如下:
class Solution {
public:
struct Node {
Node* ne[10];
Node() {
for (int i = 0; i < 10; i++) ne[i] = nullptr;
}
};
Node* root;
void insert(string&& x) {
auto p = root;
for (int i = 0; i < x.size(); i++) {
int idx = x[i] - '0';
if (!p->ne[idx]) p->ne[idx] = new Node();
p = p->ne[idx];
}
}
int calc(string&& x) {
int res = 0;
auto p = root;
for (int i = 0; i < x.size(); i++) {
int idx = x[i] - '0';
if (p->ne[idx])
p = p->ne[idx], res++;
else
break;
}
return res;
}
int longestCommonPrefix(vector<int>& a1, vector<int>& a2) {
root = new Node();
for (int x : a1) insert(to_string(x));
int res = 0;
for (int x : a2) res = max(res, calc(to_string(x)));
return res;
}
};
时空复杂度 O ( ∑ i log x i ) O(\sum_i \log x_i) O(∑ilogxi)。