LeetCode 318. Maximum Product of Word Lengths
2016-03-29 07:01
357 查看
The tough part here is on how to detect whether two words sharing common letters.
As indicate in the question, each word only contains lower case letters 'a' - 'z', we can actually correlate this problem with "in a given string, detect whether there is any duplicates". The difference here is to detect duplicates between two strings.
thus, we can use idea that if two words contains no common letters, their & operation result should be 0.
Example:
['"abc", "de"] -- > [0x111, 0x11000], thus, 0x111 & 0x11000 -> 0.
As indicate in the question, each word only contains lower case letters 'a' - 'z', we can actually correlate this problem with "in a given string, detect whether there is any duplicates". The difference here is to detect duplicates between two strings.
thus, we can use idea that if two words contains no common letters, their & operation result should be 0.
Example:
['"abc", "de"] -- > [0x111, 0x11000], thus, 0x111 & 0x11000 -> 0.
// I originally thought about to use unordered_map<int, int> to store the getBits and string size. However, it is easy to make problems. int getBits(string& str) { int bits = 0; for(char c : str) { bits |= (1 << (c - 'a')); } return bits; } int maxProduct(vector<string>& words) { int result= 0; int size = words.size(); vector<int> m(size, 0); vector<int> n(size, 0); for(int i = 0; i < size; ++i) { m[i] = getBits(words[i]); n[i] = words[i].size(); } // seems like there is no better method to get the max..... for(int i = 0; i < size; ++i) { for(int j = i + 1; j < size; ++j) { // there is no common letters. if((m[i] & m[j]) == 0) { result = max(n[i] * n[j], result); } } } return result; }
相关文章推荐
- 【灵性的觉醒】复活节的精神之旅
- jQuery UI dialog
- delphi 组件容器TObjectList代替List
- mesos 安装
- Android动画之Interpolator和AnimationSet(三)
- 一次发现underscore源码bug的经历以及对学术界『拿来主义』的思考
- julia生成指定格式的字符串.jl
- 首款Ubuntu平板开启预订 售价1600元
- 文件查找
- 转载 ASP.NET常用的正则表达式
- Oracle 占用cpu过高的处理办法
- LeetCode 268: Missing Number
- kubernetes 网络
- LeetCode 260. Single Number III
- 29. Divide Two Integers
- 使用CocoaPods可能遇到的一些问题。
- LeetCode 136. Single Number
- Android——RadioGroup和CheckBox
- 破解入门篇
- #Android Studio使用(1)#