LeetCode 318. Maximum Product of Word Lengths 题解(C++)
来源:互联网 发布:python 当前日期时间 编辑:程序博客网 时间:2024/06/05 09:26
LeetCode 318. Maximum Product of Word Lengths 题解(C++)
题目描述
- Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
举例
- Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”. - Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”. - Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.
思路
- 先创建一个长度跟words一样的整型数组vec,每个数组元素初始化为0,因为int有32个bit,所以我们用每一个元素的后26个bit来记录在每一个string中26个小写英文字母有没有出现,若出现则为该位为1,没出现则为0,这里我们用一个vec[i] |= 1 << (c - ‘a’)来实现,假设c为’d’,则‘d’减去’a’等于3,所以1右移3位为1000,之后将1000与vec[i]位或运算;
- 上面我们已经记录了每一个string中各个小写字母出现的情况,此时我们只要使用两重循环对words进行遍历,并比较每两个string是否出现共同的小写字母,这里用vec[i] & vec[j]实现,若两者位与运算后等于0,则代表这两个字符串没有共同的小写字母,这时只要将两者的乘积与已存在的最大乘积相比较,取最大的保存即可。
代码
class Solution {public: int maxProduct(vector<string>& words) { int len = words.size(); vector<int> vec(len, 0); int product = 0; for (int i = 0; i < len; ++i) { for (auto c : words[i]) { vec[i] |= 1 << (c - 'a'); } } for (int i = 0; i < len; ++i) { for (int j = i + 1; j < len; ++j) { if ((vec[i] & vec[j]) == 0) { product = max(product, static_cast<int>(words[i].size() * words[j].size())); } } } return product; }};
0 0
- LeetCode 318. Maximum Product of Word Lengths 题解(C++)
- LeetCode题解:Maximum Product of Word Lengths
- 【leetcode题解】【M】【10】318. Maximum Product of Word Lengths
- 【题解】Leetcode.318. Maximum Product of Word Lengths
- 【leetcode】318. Maximum Product of Word Lengths
- 318. Maximum Product of Word Lengths LeetCode
- [leetcode] 318. Maximum Product of Word Lengths
- LeetCode: 318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- leetcode 318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- [LeetCode]318. Maximum Product of Word Lengths
- LeetCode 318. Maximum Product of Word Lengths
- LeetCode *** 318. Maximum Product of Word Lengths
- [Leetcode] 318. Maximum Product of Word Lengths
- leetcode 318. Maximum Product of Word Lengths
- [leetcode]318. Maximum Product of Word Lengths
- 【LeetCode】318. Maximum Product of Word Lengths
- LLDB调试神器之Chisel的安装
- Android 动画详解之Tween动画
- 前端学习之为边框添加阴影
- jquery中ajax请求分类
- 二叉树系列---层次遍历二叉树
- LeetCode 318. Maximum Product of Word Lengths 题解(C++)
- nginx mysql php 搭建phabricator
- 设计模式:观察者模式【练习】
- web.xml里load-on-startup
- T-SQL经典语句
- React Native 之 Layout with Flexbox
- JS 中 onclick 事件四种传参方式
- POJ 3090 Visible Lattice Points(莫比乌斯反演)
- js 的提升效应