Skip to content

Commit 53e7299

Browse files
committed
2 parents 02a0fa2 + dc17dd5 commit 53e7299

2 files changed

Lines changed: 102 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* @lc app=leetcode.cn id=3043 lang=cpp
3+
* @lcpr version=30204
4+
*
5+
* [3043] 最长公共前缀的长度
6+
*/
7+
8+
9+
// @lcpr-template-start
10+
using namespace std;
11+
#include <algorithm>
12+
#include <array>
13+
#include <bitset>
14+
#include <climits>
15+
#include <deque>
16+
#include <functional>
17+
#include <iostream>
18+
#include <list>
19+
#include <queue>
20+
#include <stack>
21+
#include <tuple>
22+
#include <unordered_map>
23+
#include <unordered_set>
24+
#include <utility>
25+
#include <vector>
26+
// @lcpr-template-end
27+
// @lc code=start
28+
class Solution {
29+
public:
30+
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
31+
unordered_set<string> st;
32+
for(auto x:arr1){
33+
string s = to_string(x);
34+
for(int i = 1;i<=s.size();++i){ //枚举 s 的前缀,并压入哈希
35+
st.insert(s.substr(0,i));
36+
}
37+
}
38+
39+
int ans = 0;
40+
for(auto x:arr2){
41+
string s = to_string(x);
42+
for(int i = 1;i<=s.size();++i){ //寻找 arr2 与 arr1 中共同有的前缀,并统计最大值
43+
if(!st.contains(s.substr(0,i)))break;
44+
ans = max(ans,i);
45+
}
46+
}
47+
return ans;
48+
}
49+
};
50+
// @lc code=end
51+
52+
53+
54+
/*
55+
// @lcpr case=start
56+
// [1,10,100]\n[1000]\n
57+
// @lcpr case=end
58+
59+
// @lcpr case=start
60+
// [1,2,3]\n[4,4,4]\n
61+
// @lcpr case=end
62+
63+
*/
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<!--
2+
* @Author: tkzzzzzz6
3+
* @Date: 2026-05-21 11:22:00
4+
* @LastEditors: tkzzzzzz6
5+
* @LastEditTime: 2026-05-21 11:26:23
6+
-->
7+
# [3043] 最长公共前缀的长度
8+
9+
## 题目描述
10+
11+
## 思路:哈希
12+
13+
- 时间复杂度:
14+
- 空间复杂度:
15+
16+
```cpp
17+
class Solution {
18+
public:
19+
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
20+
unordered_set<string> st;
21+
for(auto x:arr1){
22+
string s = to_string(x);
23+
for(int i = 1;i<=s.size();++i){ //枚举 s 的前缀,并压入哈希
24+
st.insert(s.substr(0,i));
25+
}
26+
}
27+
28+
int ans = 0;
29+
for(auto x:arr2){
30+
string s = to_string(x);
31+
for(int i = 1;i<=s.size();++i){ //寻找 arr2 与 arr1 中共同有的前缀,并统计最大值
32+
if(!st.contains(s.substr(0,i)))break;
33+
ans = max(ans,i);
34+
}
35+
}
36+
return ans;
37+
}
38+
};
39+
```

0 commit comments

Comments
 (0)