LeetCode-318. Maximum Product of Word Lengths [C++][Java]

LeetCode-318. Maximum Product of Word Lengthsicon-default.png?t=M276https://leetcode.com/problems/maximum-product-of-word-lengths/

题目描述

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.

解题思路

【C++】

class Solution {
public:
    int maxProduct(vector<string>& words) {
        unordered_map<int, int> hash;
        int ans = 0;
        for (const string & word : words) {
            int mask = 0, size = word.size();
            for (const char & c : word) {
                mask |= 1 << (c - 'a');
            }
            hash[mask] = max(hash[mask], size);
            for (const auto& [h_mask, h_len]: hash) {
                if (!(mask & h_mask)) {
                    ans = max(ans, size * h_len);
                }
            }
        }
        return ans;
    }
};

【Java】

class Solution {
    int[][] freq;
    public int maxProduct(String[] words) {
        int len = words.length;
        freq = new int[len][26];
        for(int i=0;i<len;i++){
            char arr[]=words[i].toCharArray();
            for(int j=0;j<arr.length;j++){
                freq[i][arr[j]-'a']++;
            }
        }
        int max=0;
        for(int i=0;i<len-1;i++){
            int len_i=words[i].length();
            for(int j=i+1;j<len;j++){
                if(isOkay(i,j))
                    max=Math.max(max,len_i*words[j].length());
            }
        }
        return max;
    }
    
    boolean isOkay(int i,int j){
        for(int k=0;k<26;k++){
            if(freq[i][k]>=1 && freq[j][k]>=1)
                return false;
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值