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.
采用两层循环遍历比对,查看字符串中字符是否重复,如果不重复计算长度乘积,比对后更新最大乘积。可以看出,题目的关键是如何比对字符串中的字符是否重复,最初的想法是采用HashTable进行比对,不过大集合测试时超时了。一共有26个字符,所以可以用每一位表示一个字符是否出现,这样用int就足够表示一个字符串中出现的字符,采用按位操作就可以方便的比对两个字符串中是否有重复字符了。具体代码:
class Solution {
public:
int maxProduct(vector<string>& words) {
int rst = 0;
int sz = words.size();
vector<int> bit(sz, 0);
for(int i=0; i<sz; ++i) {
for(char ch:words[i]) bit[i] |= (1<<(ch-'a'));
}
for(int i=0; i<sz-1; ++i) {
for(int j=i+1; j<sz; ++j) {
if(bit[i]&bit[j]) continue;
rst = max(rst, (int)(words[i].size()*words[j].size()));
}
}
return rst;
}
};
另外,查看别人代码时有人按字符串长度将数组进行排序,然后在比对过程中进行预先判断剪枝,效率上应该有所提高,感兴趣的同学可以自己实现。