首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 0318 - Maximum Product of Word Lengths

LeetCode 0318 - Maximum Product of Word Lengths

作者头像
Reck Zhang
发布2021-08-11 11:57:14
发布2021-08-11 11:57:14
2780
举报
文章被收录于专栏:Reck ZhangReck Zhang

Maximum Product of Word Lengths

Desicription

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:

代码语言:javascript
复制
Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16 
Explanation: The two words can be "abcw", "xtfn".

Example 2:

代码语言:javascript
复制
Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".

Example 3:

代码语言:javascript
复制
Input: ["a","aa","aaa","aaaa"]
Output: 0 
Explanation: No such pair of words.

Solution

代码语言:javascript
复制
class Solution {
public:
    int maxProduct(std::vector<std::string>& words) {
        auto visits = std::vector<std::bitset<26>>(words.size(), 0);
        for(int i = 0; i < words.size(); i++) {
            auto word = words[i];
            for(char c : word) {
                visits[i][c - 'a'] = true;
            }
        }

        int maxLength = 0;
        for(int i = 0; i < words.size(); i++) {
            for(int j = i + 1; j < words.size(); j++) {
                if((visits[i] & visits[j]).to_ulong() == 0) {
                    maxLength = std::max(maxLength, (int)words[i].size() * (int)words[j].size());
                }
            }
        }

        return maxLength;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Maximum Product of Word Lengths
    • Desicription
    • Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档