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)

代码如下
cpp 复制代码
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空间

相关推荐
卷福同学3 小时前
QClaw内测体验,能用微信指挥AI干活了
人工智能·算法·ai编程
sali-tec3 小时前
C# 基于OpenCv的视觉工作流-章34-投影向量
图像处理·人工智能·opencv·算法·计算机视觉
xiaoye-duck3 小时前
《算法题讲解指南:递归,搜索与回溯算法--递归》--3.反转链表,4.两两交换链表中的节点,5.快速幂
数据结构·c++·算法·递归
Eward-an3 小时前
【算法竞赛/大厂面试】盛最多水容器的最大面积解析
python·算法·leetcode·面试·职场和发展
山栀shanzhi3 小时前
归并排序(Merge Sort)原理与实现
数据结构·c++·算法·排序算法
阿豪学编程3 小时前
LeetCode438: 字符串中所有字母异位词
算法·leetcode
Trouvaille ~3 小时前
【递归、搜索与回溯】专题(七):FloodFill 算法——勇往直前的洪水灌溉
c++·算法·leetcode·青少年编程·面试·蓝桥杯·递归搜索回溯
地平线开发者4 小时前
征程 6P codec decoder sample
算法·自动驾驶
地平线开发者4 小时前
征程 6X Camera 接入数据评估
算法·自动驾驶
Storynone4 小时前
【Day23】LeetCode:455. 分发饼干,376. 摆动序列,53. 最大子序和
python·算法·leetcode