Leetcode 318 Maximum Product of Word Lengths

来源:互联网 发布:淘宝代收货是什么意思 编辑:程序博客网 时间:2024/06/07 14:50

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

先把每个string进行处理

value[i] |= 1<<(tmp.charAt(j) - 'a');

当两个string里面完全不重复的时候

两个value做&会等于0

public class Solution {    public int maxProduct(String[] words) {        if(words == null || words.length == 0){            return 0;        }        int[] value = new int[words.length];        for(int i = 0; i < words.length; i++){            String tmp  = words[i];            for(int j = 0; j < tmp.length(); j++){                value[i] |= 1<<(tmp.charAt(j) - 'a');            }        }        int max = 0;        for(int i = 0; i < words.length; i++){            for(int j = i + 1; j < words.length; j++){                if((value[i] & value[j]) == 0){                    max = words[i].length() * words[j].length() > max ? words[i].length() * words[j].length() : max;                }            }        }        return max;    }}