标签:
/* * 318. Maximum Product of Word Lengths * 2016-7-5 by Mingyang * 其实因为全部都是小写的字母,用int 就可以存储每一位的信息。这就是位运算 * elements[i] |= 1 << (words[i][j] – ‘a’); //把words[i][j] 在26字母中的出现的次序变为1 * elements[i] & elements[j] // 判断是否有交集只需要两个数 按位 与 (AND)运算即可 */ public int maxProduct(String[] words) { int max = 0; Arrays.sort(words, new Comparator<String>(){ public int compare(String a, String b){ return b.length() - a.length(); } }); int[] masks = new int[words.length]; // alphabet masks for(int i = 0; i < masks.length; i++){ for(char c: words[i].toCharArray()){ masks[i] |= 1 << (c - ‘a‘); } } for(int i = 0; i < masks.length; i++){ if(words[i].length() * words[i].length() <= max) break; //prunning for(int j = i + 1; j < masks.length; j++){ if((masks[i] & masks[j]) == 0){ max = Math.max(max, words[i].length() * words[j].length()); break; //prunning } } } return max; }
318. Maximum Product of Word Lengths
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5646482.html