当前位置:网站首页>leetcode-318.最大单词长度乘积
leetcode-318.最大单词长度乘积
2022-08-02 05:15:00 【KGundam】
位运算
题目详情
给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0 。
示例1:
输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16
解释:这两个单词为 "abcw", "xtfn"。
示例2:
输入:words = ["a","ab","abc","d","cd","bcd","abcd"]
输出:4
解释:这两个单词为 "ab", "cd"。
示例3:
输入:words = ["a","aa","aaa","aaaa"]
输出:0
解释:不存在这样的两个单词。
思路:
本题的关键显然是判断两个单词是否有相同字母,如果遍历两两比较,显然复杂度较高
我们可以利用位运算,因为题目要求两个无相同字母的最长的长度乘积,所以我们可以建立一个hash
利用位左移运算得到每个字母独特的1的位置(int类型长度为32,字母一共26个,所以位置足够用)
再利用或运算|=将其赋予mask,最后每个单词都会有自己的一个独特的mask
也有可能存在一模一样mask的单词(存在重复字母比如meet和met的mask就相同)
我们只需要每次更新mask对应的length为较长的即可
在我们遍历一个个单词的时候,遍历完一个我们就用这个mask和hash里已存的mask按位与
当按位与为0时就更新ans为较长的乘积,最后我们遍历完单词,也求出了最终答案
我的代码:
class Solution
{
public:
int maxProduct(vector<string>& words)
{
unordered_map<int, int> hash; //建立hash存储字符串
int ans = 0;
for (const string & word : words) //对于每个单词
{
int mask = 0, size = word.size();
for (const char & c : word) //每个单词的每个字母
{
//c-'a'就是c到a的距离,然后将1左移这么多距离
//就能将000..01这个1移到专属于c的一个位置
//然后利用mask与它做或运算,从而将这个位置的1
//赋给mask,最后遍历完单词每个字母,就会得到一个独特的总数
mask |= 1 << (c - 'a');
}
//如果有同mask(有重复字母)的词我们取较长的
//例如meet和met具有相同的mask,我们取length就是4
hash[mask] = max(hash[mask], size);
//遍历hash寻找满足的h_mask
for (const auto& [h_mask, h_len]: hash)
{
if (!(mask & h_mask)) //按位与如果不存在相同字母
{
ans = max(ans, size * h_len);//就更新ans为较大值
}
}
}
return ans;
}
};
位运算常用技巧

边栏推荐
- 说好的女程序员做测试有优势?面试十几家,被面试官虐哭~~
- Different ways of shell scripting
- Install and use Google Chrome
- C语言操作符详解(2)
- 字节面试题:如何保证缓存和数据库的一致性
- DNS的解析流程
- 为什么4个字节的float要比8个字节的long大呢?
- Shuttle + Alluxio 加速内存Shuffle起飞
- APP Bluetooth connection test of test technology
- The virtual reality real estate display system foresees the future decoration effect in advance
猜你喜欢

Redis-----非关系数据库

Redis-cluster mode (master-slave replication mode, sentinel mode, clustering mode)

5年在职经验之谈:2年功能测试、3年自动化测试,从入门到不可自拔...

人工神经网络

【漫画】2021满分程序员行为对照表(最新版)

The virtual reality real estate display system foresees the future decoration effect in advance

Review: image saturation calculation formula and image signal-to-noise (PSNR) ratio calculation formula

APP Bluetooth connection test of test technology

leetcode括号匹配问题——32.最长有效括号

Redis(十二) - Redis消息队列
随机推荐
DNS的解析流程
leetcode每天5题-Day04
TikTok平台的两种账户有什么区别?
Mysql数据库 | 基于Docker搭建Mysql-8.0以上版本主从实例实战
Redis-cluster mode (master-slave replication mode, sentinel mode, clustering mode)
Features and installation of non-relational database MongoDB
测试环境要多少?从成本与效率说起
秒杀系统小demo
关于鸿蒙系统 JS UI 框架源码的分析
Different ways of shell scripting
ATM系统
51单片机外设篇:DS18B20
Shell 脚本不同玩法
Detailed explanation of interface in Go language
Timing task library in the language use Cron, rounding
coredns介绍
反向解析dns服务器
51 MCU peripherals: DS18B20
The virtual reality real estate display system foresees the future decoration effect in advance
Redis数据库