318. 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:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16 
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".

Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0 
Explanation: No such pair of words.

难度:medium

题目:给定一字符串数组,找出其最大length(word[i]) * length(word[j]),两个字符串不含有相同的字符。假定每个字符串只含有小写字母。如果没有这样的两个字符串返回0.

思路:BF (待更优方法)

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.

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;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018384642
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞