Leetcode - 318. 最大单词长度乘积 / python题解 / 判断两字符串是否存在相同元素

判断两字符串是否存在相同元素的思路:

  1. 利用python的set()
    两字符串进行交(集)运算,如果交集为空表示不存在相同元素

  2. (推荐⭐)位运算:一个数字的前26位对应字符串中二十六个字母出现的与否,不同字符串对应的数字,进行与运算,如果结果为0,说明没有相同字符

class Solution:
    def maxProduct(self, words) -> int:
        words = sorted(words, key=lambda x: -len(x))
        times = [0] * len(words)
        # 通过位运算,利用一个值表示一个字符串
        for i in range(len(words)):
            for j in words[i]:
                # 通过或运算将字符串中出现过字母标识一下
                times[i] |= 1 << (ord(j) - 97)
        res = 0
        for i in range(len(words)-1):
            for j in range(i+1, len(words)):
                if len(words[i]) * len(words[j]) <= res:
                    break
                if not (times[i] & times[j]):
                    res = max(len(words[i]) * len(words[j]), res)
        return res
posted @ 2020-03-20 15:19  但是我拒绝  阅读(296)  评论(0编辑  收藏  举报