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

相关推荐
普通攻击往后拉1 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
@syh.2 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发2 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕3 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI3 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.4 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
FBI HackerHarry浩5 小时前
AI大模型开发V2第四阶段线性回归
人工智能·算法·线性回归
Jerry6 小时前
LeetCode 108. 将有序数组转换为二叉搜索树
算法
蓝斯4977 小时前
Diff算法的简单介绍
算法