【LeetCode】318. Maximum Product of Word Lengths 最大单词长度乘积(Medium)(JAVA)

【LeetCode】318. Maximum Product of Word Lengths 最大单词长度乘积(Medium)(JAVA)

题目地址: https://leetcode.com/problems/maximum-product-of-word-lengths/

题目描述:

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 0 <= words.length <= 10^3
  • 0 <= words[i].length <= 10^3
  • words[i] consists only of lowercase English letters.

题目大意

给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。

解题方法

  1. 这一题主要难点在于如何判断两个字符串不存在相同的字符:最简单的方法,就是遍历两个字符串所有字符然后判断是否有相同的字符存在
  2. 暴力遍历存在的问题是每次判断两个字符串是否存在相同的字符,两个字符串都会被遍历一遍,相当于字符串被无效的多遍了 N 次
  3. 优化就是能不能只遍历一遍字符串呢?可以把每个出现的字符,当做二进制中 1 出现在相应的位置,也就是 abce 变为 10111 (1 << (‘a’ - ‘a’) + 1 << (‘b’ - ‘a’) + 1 << (‘xx’ - ‘a’)) , 因为相应字符可能出现多次,所以用或运算。 因为只有 26 个小写字母,所有用 int 存即可
  4. 如何判断两个字符串不存在相同的字符?也就是 (a & b) == 0 ,即没有相同位置的 1,就代表没有相同的字符
class Solution {
    public int maxProduct(String[] words) {
        int max = 0;
        int[] count = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            for (int k = 0; k < words[i].length(); k++) {
                int index = words[i].charAt(k) - 'a';
                count[i] |= (1 << index);
            }
        }

        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                if ((count[i] & count[j]) == 0) max = Math.max(max, words[i].length() * words[j].length());
            }
        }
        return max;
    }
}

执行耗时:8 ms,击败了99.45% 的Java用户
内存消耗:38.4 MB,击败了94.94% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值