LeetCode Maximum Product of Word Lengths
原题链接在这里:https://leetcode.com/problems/maximum-product-of-word-lengths/
用mark[i]数组来标记 words[i]都含有哪些字母,假若有个'c', 就在第三位上有个1.
通过mark[i] & mark[j] 是否为0来确定是否有相同的字母。
排序words是为了能尽量节省一些时间,去掉没有意义的比较。
Time Complexity: O(n^2), n是有多少个string.
Space: O(n), 生成了mark.
AC Java:
1 public class Solution { 2 public int maxProduct(String[] words) { 3 if(words == null || words.length == 0){ 4 return 0; 5 } 6 7 //排序words, 按照长度大到小, 为了后面节省时间 8 Arrays.sort(words, new Comparator<String>(){ 9 public int compare(String s1, String s2){ 10 return s2.length() - s1.length(); 11 } 12 }); 13 14 int [] mark = new int[words.length]; 15 for(int i = 0; i<words.length; i++){ 16 for(int j = 0; j<words[i].length(); j++){ 17 mark[i] |= (1 << words[i].charAt(j)-'a'); 18 } 19 } 20 21 int res = 0; 22 for(int i = 0; i<words.length; i++){ 23 if(words[i].length() * words[i].length() <= res){ 24 //因为words已经按照长度大到小排序了,若是words[i]长度平方还小于res, 后面的更小 25 break; 26 } 27 for(int j = i+1; j<words.length; j++){ 28 if((mark[i] & mark[j]) == 0){ 29 res = Math.max(res, words[i].length() * words[j].length()); 30 //后面更小,没有必要继续了 31 break; 32 } 33 } 34 } 35 36 return res; 37 } 38 }