【Leetcode】3043. Find the Length of the Longest Common Prefix

题目地址:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值