Maximum Product of Word
2016-02-04 06:09
351 查看
Given a string array
Example 1:
Given
Return
The two words can be
Example 2:
Given
Return
The two words can be
Example 3:
Given
Return
No such pair of words.
Analyse: As seeing this problem, I first think of brute force. For each word in the array, find other words don't share common words with it. Time exceeded.
Of course it will exceed time limit because the time complexity is O(n^4)....
Below I'll give a O(n^2) solution.
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.
Example 1:
Given
["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return
16
The two words can be
"abcw", "xtfn".
Example 2:
Given
["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return
4
The two words can be
"ab", "cd".
Example 3:
Given
["a", "aa", "aaa", "aaaa"]
Return
0
No such pair of words.
Analyse: As seeing this problem, I first think of brute force. For each word in the array, find other words don't share common words with it. Time exceeded.
class Solution { public: int maxProduct(vector<string>& words) { int result = 0; if(words.size() < 2) return result; for(int i = 0; i < words.size(); i++){ for(int j = i + 1; j < words.size(); j++){ if(!hasCommon(words[i], words[j])){ int temp = (words[i].length()) * (words[j].length()); result = max(result, temp); } } } return result; } bool hasCommon(string s1, string s2){ if(s1.empty() || s2.empty()) return false; for(int i = 0; i < s1.length(); i++){ for(int j = 0; j < s2.length(); j++){ if(s2[j] == s1[i]) return true; } } return false; } };
Of course it will exceed time limit because the time complexity is O(n^4)....
Below I'll give a O(n^2) solution.
class Solution { public: int maxProduct(vector<string>& words) { if(words.size() < 2) return 0; int result = 0; vector<int> bits(words.size(), 0); for(int i = 0; i < words.size(); i++){ for(int j = 0; j < words[i].size(); j++) bits[i] |= 1 << (words[i][j] - 'a'); } for(int i = 0; i < words.size(); i++){ for(int j = i; j < words.size(); j++){ if(!(bits[j] & bits[i])){ int temp = words[i].length() * words[j].length(); result = max(result, temp); } } } return result; } };
相关文章推荐
- LFU Cache
- [CSS] :not Selector
- QT自绘任务表,很不错的说~
- 全国自然科学一等奖是主流,还是歪道?
- 不是什么时候都可以用栈来声明对象并使用(自动释放)——Delphi里到处都是编译器魔法,并且自动帮助实例化界面元素指针
- SpatialHadoop中空间索引系列之(三)格网索引原理
- 浅析动态web编程语言--Servlet
- 浅谈正则表达式
- 【Android】2.1 PhonewordApp—第1个Android应用程序
- 网页设计html+css基础知识汇总
- 关于进行java学习和Android开发,本人认为的一些基础的入门必需知识,全程手敲
- 疯狂高效的一天
- Groupon面经Prepare: Max Cycle Length
- SpatialHadoop中空间索引系列之(二)空间对象索引原理
- Leetcode #93 Restore IP Addresses
- 【Android】2.0 第2章 初识Android App
- *Gray Code
- 165. Compare Version Numbers
- Java带进度条的文件上传
- Subsets