码迷,mamicode.com
首页 > 其他好文 > 详细

318. Maximum Product of Word Lengths

时间:2016-07-06 13:24:35      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!