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;
        }
    }
    
  • 相关阅读:
    五步搞定Android开发环境部署
    centos7安装MongoDB3.4
    java数据结构之三叉链表示的二叉树
    java数据结构之二叉树遍历的非递归实现
    java数据结构之二叉树的定义和递归实现
    java数据结构之树
    java数据结构之递归算法
    java数据结构之(堆)栈
    redis主从复制配置
    Redis 发布订阅
  • 原文地址:https://www.cnblogs.com/mapoos/p/14820196.html
Copyright © 2011-2022 走看看