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:
Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
题意:
给定一堆单词,要求找出俩单词长度的最大乘积,要求俩单词不能有相同字母。
思路:
判断noOverLapping: 用2个set分别标记俩单词, 扫一遍set,若发现某个字母被同时标记过,则有重叠。
取最大乘积长度:两重for循环,两两比较,更新最大值。
代码:
class Solution {
public int maxProduct(String[] words) {
int result = 0;
for (int i = 0; i < words.length; ++i) {
for (int j = i + 1; j < words.length; ++j) {
int tmp = words[i].length() * words[j].length();
if ( noOverLapping(words[i], words[j])&& tmp > result) {
result = tmp;
}
}
}
return result;
}
private boolean noOverLapping(String a , String b){
boolean[] setA = new boolean[256];
boolean[] setB = new boolean[256]; for(int i = 0; i < a.length(); i++){
setA[a.charAt(i)] = true;
} for(int i = 0; i < b.length(); i++){
setB[b.charAt(i)] = true;
} for(int i = 0; i < 256; i++){
if(setA[i] == true && setB[i] == true){
return false;
}
} return true;
}
}
可以进一步优化:对于如何判断俩单词有没有相同字母,可用位向量表示每个字母是否出现即可,俩位向量异或即可得出是否有相同字母。
public class Solution {
public int maxProduct(String[] words) {
final int n = words.length;
final int[] hashset = new int[n]; for (int i = 0; i < n; ++i) {
for (int j = 0; j < words[i].length(); ++j) {
hashset[i] |= 1 << (words[i].charAt(j) - 'a');
}
} int result = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int tmp = words[i].length() * words[j].length();
if ((hashset[i] & hashset[j]) == 0 && tmp > result) {
result = tmp;
}
}
}
return result;
}
}