318. Maximum Product of Word Lengths,maximumlengths

來源:互聯網
上載者:User

318. Maximum Product of Word Lengths,maximumlengths

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.     

    public static int maxProduct(String[] words){        int[] arri = new int[words.length];        for (int i = 0; i < words.length; i++) {            for (int j = 0; j < words[i].length(); j++) {                arri[i] |= 1<<(words[i].charAt(j)-'a');            }        }                int ans = 0;        for (int i = 0; i < words.length-1; i++) {            for (int j = i+1; j < words.length; j++) {                if ((arri[i] & arri[j]) == 0) {// 沒有重複的字母                    ans = Math.max(ans, words[i].length()*words[j].length());                }            }        }        return ans;    }

移位元運算符:

1 << 0 => 11 << 1 => 21 << 2 => 41 << 3 => 81 << 4 => 161 << 5 => 321 << 6 => 641 << 7 => 1281 << 8 => 2561 << 9 => 5121 << 10 => 10241 << 11 => 20481 << 12 => 40961 << 13 => 81921 << 14 => 163841 << 15 => 327681 << 16 => 655361 << 17 => 1310721 << 18 => 2621441 << 19 => 5242881 << 20 => 10485761 << 21 => 20971521 << 22 => 41943041 << 23 => 83886081 << 24 => 167772161 << 25 => 33554432 words[i] 對應著arri[i]:words[i]中的每個單詞編碼後得到arri[i]注釋處相交等於0說明有重複字母。  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.