0318. Maximum Product of Word Lengths (M)

Maximum Product of Word Lengths (M)

题目

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] consists only of lowercase English letters.

题意

给定一系列单词,在其中找到字符不重叠的两个单词,使它们长度的乘积最大。

思路

直接暴力就能过。


代码实现

Java

class Solution {
    public int maxProduct(String[] words) {
        int ans = 0;
        for (int i = 0; i < words.length - 1; i++) {
            for (int j = i + 1; j < words.length; j++) {
                if (judge(words[i], words[j])) {
                    ans = Math.max(ans, words[i].length() * words[j].length());
                }
            }
        }
        return ans;
    }

    private boolean judge(String a, String b) {
        boolean[] exist = new boolean[26];
        for (char c : a.toCharArray()) {
            exist[c - 'a'] = true;
        }
        for (char c : b.toCharArray()) {
            if (exist[c - 'a']) {
                return false;
            }
        }
        return true;
    }
}
posted @ 2021-05-27 22:56  墨云黑  阅读(43)  评论(0编辑  收藏  举报