LeetCode-318 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.

 

题目大意

给定一组字符串,要求求出两个字符串的长度乘积最大的(要求两个字符串中不包含相同的字母)。

(PS:字符串中只有小写字母)

 

示例

E1

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

E2

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

 

解题思路

用数组保存该字符串的字节转码(例如:abc = ’111‘,abd = ’1011‘,cd = ’1100‘),依次访问之前的字符转码,如果之间不存在共有的字母,则计算两个字母的长度乘积。

 

复杂度分析

时间复杂度:O(N2)

空间复杂度:O(N)

 

代码

class Solution {
public:
    int maxProduct(vector<string>& words) {
        vector<int> bit(words.size());
        int res = 0;
        
        for(int i = 0; i < words.size(); ++i) {
            // 将当前字符串的转码保存记录到数组中
            for(char c : words[i])
                bit[i] |= 1 << (c - 'a');
            // 访问当前字符串之前的所有转码
            for(int j = 0; j < i; ++j) {
                // 如果两个字符串之间不存在共有字母,则保存更大的长度乘积
                if(!(bit[j] & bit[i]))
                    res = max(res, (int)(words[i].length() * words[j].length()));
            }
        }
        
        return res;
    }
};

 

转载于:https://www.cnblogs.com/heyn1/p/11176455.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值