剑指 Offer II 005. 单词长度的最大乘积

【python 快速版】

class Solution:

    def maxProduct(self, words: List[str]) -> int:
                #计算两个字符串是否有相同字符,没有 则返回两字符串长度的乘机
        def compareString(str1 , str2):
            #将str2 放入字典
            setstr2 = set(str2)
            flag = False
            for i in str1:
                if i in setstr2:
                    flag = True

            if not flag:
                return len(str1) *len(str2)
            return 0

        #记录最大值
        maxLength = 0
        
        for index in range(len(words)):
            for s in range(index+1,len(words)):
                maxnum = compareString(words[index],words[s])
                if maxLength <maxnum:
                    maxLength = maxnum
        
        return maxLength

【算法思想】

遍历字符串数组 words 中的每一对单词,判断这一对单词是否有公共字母,如果没有公共字母,则用这一对单词的长度乘积更新单词长度的最大乘积

当然这种做法时间复杂度很高。该复杂度高于O(n平方)

方法二、位运算

【算法思想】优化主要降低字符串比较时的复杂度;方法是:将小写的26个字母,转化为0~25的二进制掩码的形式,mask[i]&mask[j]=0时说明没有相同字母。 思想很容易,实现有点困难。

class Solution:

    def maxProduct(self, words: List[str]) -> int:
        #现将所有的word的mask 计算出来
        maskList = [reduce(lambda a,b : a | (1<<(ord(b)-ord("a")))  ,word,0 ) for word in words]
        maxlen = 0
        for x , y in product(zip(maskList,words),repeat=2):
            if x[0] & y[0] == 0 :         #表示没有相同字母
                maxlen = max(maxlen,len(x[1]) * len(y[1]))
        return maxlen

【分析】

复杂度分析

时间复杂度:O(L + n^2),其中 L 是数组words 中的全部单词长度之和,n 是数组 words 的长度。预处理每个单词的位掩码需要遍历全部单词的全部字母,时间复杂度是 O(L),然后需要使用两重循环遍历位掩码数组 masks 计算单词长度的最大乘积,时间复杂度是 O(n^2),因此总时间复杂度是 O(L + n^2)。

空间复杂度:O(n),其中 n 是数组 words 的长度。需要创建长度为 n 的位掩码数组 masks。

【python知识点】

python 内置函数 ord ,返回表示指定字符 unicode 编码的数字。

reduce 函数, 现在不是内置函数。

from functools import reduce

reduce 有三个参数,第一个是函数function,第二个是序列sequence,第三个是initial,为初始值,默认为None

def reduce(function, sequence, initial=_initial_missing):
    """
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
...

"""
reduce(函数,序列[,初始])-> 值
将两个参数的函数累积应用于序列的项目,从左到右,从而将序列减少到单个值。
例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算((((1+2)+3)+4)+5)。

如果 initial 存在,则将其放在项目之前在计算中的序列,并作为默认值时序列为空。
"""

[reduce(lambda a,b : a | (1<<(ord(b)-ord("a")))  ,word,0 )]  其中 | 为或运算 , a接传入默认值0 , 0| 任何值 =  任何值;

product(A,B)函数,返回A和B中的元素组成的笛卡尔积的元组,具体见如下代码

from functools import reduce
from itertools import product


print(ord('b')-ord('a'))
print(0 | 1<<(ord('b')-ord('a')))
print(reduce(lambda a,b : a | (1<<(ord(b)-ord("a"))),"d",0 ))
print([(x,y) for x , y in product(zip([1,2],["ab","cd"]),repeat=2)])

输出: 

1
2
8
[((1, 'ab'), (1, 'ab')), ((1, 'ab'), (2, 'cd')), ((2, 'cd'), (1, 'ab')), ((2, 'cd'), (2, 'cd'))]
class product(object):
    """
    product(*iterables, repeat=1) --> product object
    
    Cartesian product of input iterables.  Equivalent to nested for-loops.
    
    For example, product(A, B) returns the same as:  ((x,y) for x in A for y in B).
    The leftmost iterators are in the outermost for-loop, so the output tuples
    cycle in a manner similar to an odometer (with the rightmost element changing
    on every iteration).
    
    To compute the product of an iterable with itself, specify the number
    of repetitions with the optional repeat keyword argument. For example,
    product(A, repeat=4) means the same as product(A, A, A, A).
    
    product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)
    product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...
    """
...
Product(*iterables, repeat=1) - > product object
输入迭代的笛卡尔积。相当于嵌套的 for - 循环。
例如,product(A, B) 返回相同的结果:((x,y) for x in A for y in B)。
最左边的迭代器在最外层的 for - 循环中,所以输出元组
以类似于里程表的方式循环(最右边的元素发生变化每次迭代)。
要计算迭代与自身的乘积,请指定数字
带有可选的重复关键字参数的重复次数。例如,
product(A, repeat=4) 与 product(A, A, A, A) 的含义相同。
product('ab', range(3)) - > ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) (' b',2)
product((0,1), (0,1), (0,1)) - > (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...
“”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑾怀轩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值