318-Maximum Product of Word Lengths
Description
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.
問題描述
給定字串陣列words, 返回words中沒有相同字母的兩個字串的最大的長度之積。words中的單詞都只有小寫字母。如果沒有字母都不相同的兩個字串, 返回0
問題分析
關鍵是使用一個整數來保留字串words[i]中字母的資訊, ‘a’對應最低位為1, ‘b’對應次低位為1, 依次類推。
然後遍歷字串, 找出最大的長度之積即可
解法
class Solution {
public static int maxProduct(String[] words) {
if(words == null || words.length == 0) return 0;
int len = words.length;
int[] value = new int[len];
for(int i = 0; i < len; i++){
String tmp = words[i];
//關鍵是這裡的轉換
for(int j = 0; j < tmp.length(); j++) value[i] |= 1 << (tmp.charAt(j) - 'a');
}
int maxProduct = 0;
for(int i = 0; i < len; i++){
for(int j = i + 1; j < len; j++){
//注意這裡使用按位與判斷
if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length() > maxProduct)){
maxProduct = words[i].length() * words[j].length();
}
}
}
return maxProduct;
}
}
相關文章
- Product Quantization
- A. Least ProductAST
- ABC 322 E Product Developmentdev
- SAP EPD - Enterprise Product Developmentdev
- 【Lintcode】1415. Residual Product
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- 238. Product of Array Except Self
- LeetCode | 152. Maximum Product SubarrayLeetCode
- 【Lintcode】191. Maximum Product Subarray
- 【Lintcode】1322. Product Equal B
- 給Product新增自定義屬性
- [LeetCode] 238. Product of Array Except SelfLeetCode
- c#訪問WooCommerce 生成ProductC#
- [ARC182C] Sum of Number of Divisors of Product
- Product Backlog:終極任務清單
- Hackerrank GCD Product(莫比烏斯反演)GC
- pdf轉word格式PDF to word for MacMac
- SAP Commerce Cloud 的 Product Carousel Component 介紹Cloud
- 《價值流動-Project To Product》讀後感Project
- SAP Commerce Cloud Product Review 的新增邏輯CloudView
- 實戰流量提升方法優化Product Ads優化
- SAP CRM Product category的決定邏輯Go
- 錯誤訊息sales area is not assigned for the header productHeader
- 如何使用ABAP程式碼建立SAP Product CategoryGo
- Hello Word!
- hello word
- Word Ladder
- word 2021:Word 2021 LTSC for Mac 中文版Mac
- 敏捷開發:Scrum 中的 Product Backlog 介紹敏捷Scrum
- word-break 和 word-wrap 的區別
- word-wrap同word-break的區別
- pdf 轉 word
- word小程式
- Leetcode Word SearchLeetCode
- Java操作WordJava
- Character Specifications for A Word
- linux - word frequencyLinux
- Python操作WordPython