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

【Leetcode】Maximum Product of Word Lengths

时间:2016-05-27 12:57:27      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/maximum-product-of-word-lengths/

题目:
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.

思路:
一个int装化为2进制是32位,利用其中的26位来表示一个单词是否出现了某个字母,在比较两个单词是否含有共同字母的时候就可以将两者的int数字相与,若结果为0,则有共同字母。

算法:

    public int maxProduct(String[] words) {
        int max = 0;
        int words_value[] = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < words[i].length(); j++) {
                char c = words[i].charAt(j);
                words_value[i] = words_value[i] | (1 << (c - ‘a‘));// 把1左移多少位
            }
        }
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                int product = 0;
                if ((words_value[i] & words_value[j]) == 0) {
                    product = words[i].length() * words[j].length();
                }
                max = Math.max(max, product);
            }
        }
        return max;
    }

【Leetcode】Maximum Product of Word Lengths

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51483656

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