zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    transition过渡效果
    transform旋转变换效果
    让字体在div容器中垂直居中
    背景图片浮动居中
    解决图片浮动调节不了的问题(使用vertical-align属性)
    box-shadow向元素添加阴影效果
    hr中间插入字体
    codeforces 659D . Bicycle Race 几何
    codeforces 659E . New Reform 强连通
    codeforces 552 E. Vanya and Brackets 表达式求值
  • 原文地址:https://www.cnblogs.com/heyn1/p/11176455.html
Copyright © 2011-2022 走看看