• 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;
        }
    }
    
  • 相关阅读:
    MySQL基础
    DNS域名解析服务
    仿Mars MP3播放器项目5
    仿Mars MP3播放器项目4
    仿Mars MP3播放器项目3
    仿Mars MP3播放器项目2
    仿Mars MP3播放器项目1
    JAVA 随记1
    Redis和Memcache的区别
    php用smtp发送邮件
  • 原文地址:https://www.cnblogs.com/mapoos/p/14820196.html
Copyright © 2020-2023  润新知