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(32bit)前24bit分別表示a-z的24個字符是否出現。0表示沒有出現,1表示出現。然後字符串兩兩做"與"運算,結果爲0表示互相不包含相同字符串。再採用"打擂臺法"得出最大值即可。

代碼:

class Solution {
    public int maxProduct(String[] words) {
          // 核心:如何判斷兩個word"交叉",採用位運算。
        int[] wordBit = new int[words.length];
        for(int i = 0;i<words.length;i++){
            String word = words[i];
            for(int j= 0 ;j<word.length();j++){
                wordBit[i] |= 1<<(word.charAt(j) -'a');
            }
        }
        int max = 0;
        for(int i =0;i<wordBit.length;i++){
            for(int j=i+1;j<wordBit.length;j++){
                if((wordBit[i] & wordBit[j]) == 0){
                    // 無"交叉"
                    int l = words[i].length() *words[j].length();
                            max = max > l ? max : l;
                }
            }
        }
        return max;
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章