zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    Python开发——数据类型【字典】
    Python开发——数据类型【元祖】
    Python开发——数据类型【列表】
    Python开发——基础
    Python开发——数据类型【运算符】
    c#中IList<T>与List<T>
    观察者模式(Observer Pattern)
    中介者模式(Mediator Pattern)
    策略模式(Strategy Pattern)
    命令模式
  • 原文地址:https://www.cnblogs.com/mapoos/p/14820196.html
Copyright © 2011-2022 走看看