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.git
Example 1:數組
Input: ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn".
Example 2:less
Input: ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd".
Example 3:code
Input: ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words.
難度:medium字符串
題目:給定一字符串數組,找出其最大length(word[i]) * length(word[j]),兩個字符串不含有相同的字符。假定每一個字符串只含有小寫字母。若是沒有這樣的兩個字符串返回0.string
思路:BF (待更優方法)it
Runtime: 443 ms, faster than 11.27% of Java online submissions for Maximum Product of Word Lengths.
Memory Usage: 40.4 MB, less than 30.44% of Java online submissions for Maximum Product of Word Lengths.io
class Solution { public int maxProduct(String[] words) { int n = words.length, maxProductLength = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (!isWordsOverlap(words[i], words[j])) { maxProductLength = Math.max(maxProductLength, words[i].length() * words[j].length()); } } } return maxProductLength; } private boolean isWordsOverlap(String word1, String word2) { int[] digit1 = new int[26]; int[] digit2 = new int[26]; for (int i = 0; i < word1.length(); i++) { digit1[word1.charAt(i) - 'a']++; } for (int i = 0; i < word2.length(); i++) { digit2[word2.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if (digit1[i] > 0 && digit2[i] > 0) { return true; } } return false; } }