-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_318.java
45 lines (41 loc) · 1.38 KB
/
prob_318.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 318. Maximum Product of Word Lengths
* Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
* If no such two words exist, return 0.
*/
public class prob_318 {
public static void main(String[] args) {
Solution_318 solution = new Solution_318();
String[] words = {"abcw","baz","foo","bar","xtfn","abcdef"};
System.out.println(solution.maxProduct(words));
}
}
/**
* Solution using matrix multiplication
* Time Complexity = O(n^2) where n is the number of words
* Space Complexity = O(n)
*/
class Solution_318 {
int[][] alphabetMatrix;
public int maxProduct(String[] words) {
alphabetMatrix = new int[words.length][26];
int max = 0;
for (int i = 0; i < words.length; i++) {
for (char c : words[i].toCharArray()) {
alphabetMatrix[i][c-'a'] = 1;
}
}
for (int i = 0; i < words.length; i++) {
for (int j = i; j < words.length; j++) {
if(this.matMult(i, j)) max = Math.max(max, words[i].length()*words[j].length());
}
}
return max;
}
private boolean matMult(int i, int j) {
for (int k = 0; k < 26; k++) {
if(alphabetMatrix[i][k] == 1 && alphabetMatrix[j][k] == 1) return false;
}
return true;
}
}