欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > LC 318. Maximum Product of Word Lengths

LC 318. Maximum Product of Word Lengths

2025/2/24 9:17:27 来源:https://blog.csdn.net/ok1382038/article/details/144447343  浏览:    关键词:LC 318. Maximum Product of Word Lengths

题目描述

Leetcode 318
给定一个只包含小写字母字符串数组,返回两个没有共同字符的字符串长度乘积的最大值

题目思路

简单的思路是将字符串编码成长度为26的数组,然后两两字符串比较,这样可以将O(L1L2)的比较压缩到O(2626)。

位图bitmap

这道题目可以使用bitmap将压缩成一个26位二进制,每一位0/1表示是否有这个字符串,类似one-hot encoding。然后两个字符串比较时间复杂度可以压缩成 bit(A) & bit(B) 也就是 O(1)

代码如下
class Solution {
public:int maxProduct(vector<string>& words) {//bitmap可以直接将字符串根据字符one-hot转化成26位二进制unordered_map<int, int> bitmap;// key是bit,value是拥有bit分布的最长长度for (int i=0; i<words.size(); i++) {int bitmask = 0;for (char ch: words[i]) {int _idx = ch-'a';bitmask |= 1<<_idx;}// ab 和 aabb具有相同one-hot编码bitmap[bitmask] = max(bitmap[bitmask], (int)words[i].length());}int res = 0;for (const auto& p1 : bitmap) {for (const auto& p2: bitmap) {if ((p1.first & p2.first)==0) {res = max(res, p1.second * p2.second);}}}return res;}
};

时间复杂度: O ( L + N 2 ) \mathcal{O}(L + N^2) O(L+N2) L为字符串数组总长度,N为hashmap空间
空间复杂度: O ( N ) \mathcal{O}(N) O(N) N为Hashmap空间

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词