问题描述
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".
思路
将 string 转化为 int,通过按位与来判断两个 string 是否含有相同的字母
提交
public class Solution {
public int maxProduct(String[] words) {
int size = words.length;
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
nums[i] = wordToNum(words[i]);
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if ((nums[i] & nums[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max == Integer.MIN_VALUE ? 0 : max;
}
public int wordToNum(String string) {
int result = 0;
int size = string.length();
for (int i = 0; i < size; i++) {
result |= 1 << (string.charAt(i) - 'a');
}
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。