zoukankan      html  css  js  c++  java
  • 318. Maximum Product of Word Lengths

    好久没leetcode一下了,以后每天1题,坚持一下~

    https://leetcode.com/problems/maximum-product-of-word-lengths/

    
    Total Accepted: 9706 Total Submissions: 24927 Difficulty: Medium
    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:
    Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
    Return 16
    The two words can be "abcw", "xtfn".
    
    Example 2:
    Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
    Return 4
    The two words can be "ab", "cd".

    sol: 将每个单词对应到一个数。为增加效率,长度也可提前算好。

    class Solution(object):
        def maxProduct(self, words):
            """
            :type words: List[str]
            :rtype: int
            """
            n = len(words)
            word_map,len_map = [],[]
            for word in words:
                word_map += sum(1<<(ord(x)-ord('a')) for x in set(word)),
                len_map += len(word),
            
            ans = 0
            for i in range(n):
                for j in range(i+1,n):
                    if word_map[i] & word_map[j] == 0:
                        ans = max( len_map[i]*len_map[j], ans )
            
            return ans                              
                
    每天一小步,人生一大步!Good luck~
  • 相关阅读:
    c++ 有序二叉树的应用
    c++ 二叉树的遍历
    c++ 创建二叉树
    c++ 双向链表 的查找和删除
    c++ 双向循环链表
    c++ 双向链表
    Jzoj4209 已经没有什么好害怕的了
    Jzoj4209 已经没有什么好害怕的了
    后缀自动机转后缀树模板
    后缀自动机转后缀树模板
  • 原文地址:https://www.cnblogs.com/jkmiao/p/5170772.html
Copyright © 2011-2022 走看看