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.
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags分析:
总是查找两个字符串是否有相同的字符(耗时耗力),没有获取两者的长度乘积,有就无视两者。
笨办法处理(超时):
class Solution { public: int maxProduct(vector<string>& words) { if(words.empty()) return 0; int result=0; for(int i=0;i<words.size()-1;i++) { for(int j=i+1;j<words.size();j++) { if(!isCommom(words[i],words[j]) && words[i].size()*words[j].size() > result) result=words[i].size()*words[j].size(); } } return result; } bool isCommom(string stra,string strb)//判断是否有共同元素 { if(stra.size()==0 || strb.size()==0) return false; sort(stra.begin(),stra.end()); sort(strb.begin(),strb.end()); int i=0; int j=0; if(stra[stra.size()-1] < strb[0] || stra[0] > strb[strb.size()-1]) return false; while(i<stra.size() && j<strb.size()) { if(stra[i] < strb[j]) i++; else if(stra[i] > strb[j]) j++; else return true; } return false; } };
别人的分析:
漂亮,这种位处理方法对于字符的处理似乎很常用,在前面某个题目见过这种做法!
根据题目的描述,我们可知,最耗时的地方在于判断两个字符串中是否存在重复的字符。
一提到判断重复字符,脑海中马上浮现哈希大法。
又看到题目要保证字符串均为小写字母,也就说总共26个字母,我们需要26位,一个int足矣。
我们自定义,如果某字符出现,该bit置1,否则置0.
则比较两个字符串是否有重复字符,就是让这两个标志int 进行与操作,结果为0则表明没有重复字符。
好的,本题的难点已结束。code如下:
易知时间复杂度为O(n2),空间复杂度为O(n),其中n为所有字符串的个数。
class Solution { public: int maxProduct(vector<string>& words) { if(words.empty()) return 0; vector<int> isDuplicate(words.size(),0); int nSize = words.size(); //处理的很漂亮 for(int i = 0; i < nSize; i++) { //将第i个字符串转化成在1个int里,比如abc,将被转化成0000...0111 int length = words[i].size(); for(int j = 0; j < length; j++) isDuplicate[i] |= 1 << (words[i][j] - 'a'); } int maxMul = 0; for(int i = 0; i < nSize -1; i++) { for(int j = i +1; j < nSize; j++) { if((isDuplicate[i] & isDuplicate[j]) == 0)//相与结果为0,则说明无重复字符 { int tempMul = words[i].size()*words[j].size(); if(maxMul < tempMul) maxMul = tempMul; } } } return maxMul; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51660360
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
热门源码