318. Maximum Product of Word Lengths,maximumlengths
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.
public static int maxProduct(String[] words){ int[] arri = new int[words.length]; for (int i = 0; i < words.length; i++) { for (int j = 0; j < words[i].length(); j++) { arri[i] |= 1<<(words[i].charAt(j)-'a'); } } int ans = 0; for (int i = 0; i < words.length-1; i++) { for (int j = i+1; j < words.length; j++) { if ((arri[i] & arri[j]) == 0) {// 沒有重複的字母 ans = Math.max(ans, words[i].length()*words[j].length()); } } } return ans; }
移位元運算符:
1 << 0 => 11 << 1 => 21 << 2 => 41 << 3 => 81 << 4 => 161 << 5 => 321 << 6 => 641 << 7 => 1281 << 8 => 2561 << 9 => 5121 << 10 => 10241 << 11 => 20481 << 12 => 40961 << 13 => 81921 << 14 => 163841 << 15 => 327681 << 16 => 655361 << 17 => 1310721 << 18 => 2621441 << 19 => 5242881 << 20 => 10485761 << 21 => 20971521 << 22 => 41943041 << 23 => 83886081 << 24 => 167772161 << 25 => 33554432 words[i] 對應著arri[i]:words[i]中的每個單詞編碼後得到arri[i]注釋處相交等於0說明有重複字母。