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

相关推荐
lamentropetion9 小时前
E - Equal Tree Sums CF1656E
算法
代码游侠9 小时前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
Xの哲學9 小时前
Linux Platform驱动深度剖析: 从设计思想到实战解析
linux·服务器·网络·算法·边缘计算
逑之9 小时前
C语言笔记11:字符函数和字符串函数
c语言·笔记·算法
栈与堆9 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
不知名XL9 小时前
day20 回溯算法part02
算法
嵌入式进阶行者9 小时前
【算法】TLV格式解析实例:华为OD机考双机位A卷 - TLV解析 Ⅱ
数据结构·c++·算法
OC溥哥9999 小时前
Paper MinecraftV3.0重大更新(下界更新)我的世界C++2D版本隆重推出,拷贝即玩!
java·c++·算法
Jayden_Ruan9 小时前
C++蛇形方阵
开发语言·c++·算法
星火开发设计10 小时前
C++ map 全面解析与实战指南
java·数据结构·c++·学习·算法·map·知识