Every day a Leetcode
题目来源:3043. 最长公共前缀的长度
解法1:字符串 + 集合
数字不好比较前缀,把它们转换成字符串再进行比较。
将数组 arr1 的元素的所有前缀插入到一个字符串集合 strSet 中,遍历数组 arr2 的元素 x,转换成字符串 s,取 s 的前缀在集合中搜索,若找到,更新最长公共前缀的长度。
最后返回最大值即可。
代码:
/*
* @lc app=leetcode.cn id=3043 lang=cpp
*
* [3043] 最长公共前缀的长度
*/
// @lc code=start
class Solution
{
public:
int longestCommonPrefix(vector<int> &arr1, vector<int> &arr2)
{
set<string> strSet;
for (int &x : arr1)
{
string s = to_string(x);
for (int i = 1; i <= s.length(); i++)
strSet.insert(s.substr(0, i));
}
int ans = 0;
for (int &x : arr2)
{
string s = to_string(x);
for (int len = 1; len <= s.length(); len++)
{
string temp = s.substr(0, len);
if (strSet.count(temp))
ans = max(ans, len);
}
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O((n+m)log2U),,其中 n 为数组 arr1 的长度,m 为数组 arr2 的长度,U 为数组元素的最大值。
空间复杂度:O(nlog2U),,其中 n 为数组 arr1 的长度,U 为数组元素的最大值。