單詞長度,最大乘積
阿新 • • 發佈:2021-08-30
設計的知識點
a|=b的意義是a = a | b
將int數值,作為二進位制進行比較,各位不同時返回1
int a = 5; // 0000 0101 int b = 3; // 0000 0011 a |= b; // 0000 0011
&=與|比較方式相同,邏輯相反
兩位不同時直接返回0
int a = 5; // 0000 0101 int b = 3; // 0000 0011 a &= b; // 0000 0001
<<左進位,不分正負,低位補0
>>右進位,分正負,正數高位補0,負數高位補1
>>>不分正負,右移高位補0
給定一個字串陣列 words,請計算當兩個字串 words[i] 和 words[j] 不包含相同字元時,它們長度的乘積的最大值。假設字串中只包含英語的小寫字母。如果沒有不包含相同字元的一對字串,返回 0。
class Solution { public int maxProduct(String[] words) { int length = words.length; int[] flags = new int[length]; int ans = 0; for(int i = 0 ; i < length;i++) for(int j = 0; j < words[i].length(); j++){ flags[i] |= 1 << (words[i].charAt(j) - 'a'); }for(int i = 0;i < length; i++) for(int j = i+1;j < length;j++){ if((flags[i] & flags[j]) == 0){ if((words[i].length() * words[j].length()) > ans) ans = words[i].length() * words[j].length(); } }return ans; } }