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

相关推荐
Paul_09206 分钟前
golang编程题
开发语言·算法·golang
颜酱11 分钟前
用填充表格法-继续吃透完全背包及其变形
前端·后端·算法
夏秃然14 分钟前
打破预测与决策的孤岛:如何构建“能源垂类大模型”?
算法·ai·大模型
氷泠18 分钟前
课程表系列(LeetCode 207 & 210 & 630 & 1462)
算法·leetcode·拓扑排序·反悔贪心·三色标记法
代码or搬砖21 分钟前
JVM垃圾回收器
java·jvm·算法
老鼠只爱大米23 分钟前
LeetCode算法题详解 15:三数之和
算法·leetcode·双指针·三数之和·分治法·three sum
客卿12323 分钟前
C语言刷题--合并有序数组
java·c语言·算法
Qhumaing24 分钟前
C++学习:【PTA】数据结构 7-1 实验6-1(图-邻接矩阵)
c++·学习·算法
菜鸟233号38 分钟前
力扣416 分割等和子串 java实现
java·数据结构·算法·leetcode
Swift社区44 分钟前
LeetCode 469 凸多边形
算法·leetcode·职场和发展