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空间

相关推荐
罗湖老棍子13 小时前
荒岛野人(信息学奥赛一本通- P1637)(洛谷-P2421)
算法·数论·枚举·裴蜀定理·扩展欧几里得·扩展中国剩余定理
朝朝辞暮i13 小时前
C++ 第 40 章:ROS2 Publisher + Timer + Subscriber + Callback + Executor 完整闭环
开发语言·c++·算法·ros2
400分13 小时前
具身智能系列之从零到「机械臂会放试管」:π0.5 VLA 真机部署完全指南【第一节】
算法
小宋102113 小时前
一套服务托管多个 LoRA:适配器加载、租户隔离与热切换实战
大数据·人工智能·算法
Rosanci13 小时前
Codex 下载与本地部署实战:从安装到运行全流程指南
开发语言·前端·算法·chatgpt·codex
我爱工作&工作love我13 小时前
P14358 [CSP-J 2025] 座位
算法
旖旎夜光13 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
朝朝辞暮i13 小时前
C++ 第 38 课:线程、SingleThreadedExecutor、MultiThreadedExecutor、Callback Group
开发语言·c++·算法·ros2
(Charon)13 小时前
【C++面试】互斥锁与读写锁:使用场景、实现原理与写饥饿问题
c++·算法
longlongzihan13 小时前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯