Leetcode - Maximum Product of Wo
2016-10-14 本文已影响6人
Richardo92
My code:
public class Solution {
public int maxProduct(String[] words) {
int max = 0;
int len = words.length;
int[] bits = new int[len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < words[i].length(); j++) {
bits[i] |= 1 << (words[i].charAt(j) - 'a');
}
}
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if ((bits[i] & bits[j]) == 0) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
}
reference:
https://discuss.leetcode.com/topic/35539/java-easy-version-to-understand
这道题目我一开始的做法就是申请一个
boolean[] dict = new boolean[26];
下面是我的代码:
My code:
public class Solution {
public int maxProduct(String[] words) {
int max = 0;
for (int i = 0; i < words.length; i++) {
boolean[] dict = new boolean[26];
for (int k = 0; k < words[i].length(); k++) {
dict[words[i].charAt(k) - 'a'] = true;
}
for (int j = i + 1; j < words.length; j++) {
if (words[j].length() <= max / words[i].length()) {
continue;
}
boolean doesIntersect = false;
for (int k = 0; k < words[j].length(); k++) {
if (dict[words[j].charAt(k) - 'a']) {
doesIntersect = true;
break;
}
}
if (!doesIntersect) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
}
然后也尽量剪枝了。但还是很慢。
看了答案后,发现是用 Bit manipulation 做,真的很巧妙。
Anyway, Good luck, Richardo! -- 10/13/2016