zoukankan      html  css  js  c++  java
  • Leetcode

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

    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
    
  • 相关阅读:
    javaweb地图定位demo
    java基础循环
    java实现时钟
    栈和队列
    线程池
    java死锁及解决方案
    克隆
    算法与数据结构基础一
    重定向与转发的区别
    省选模拟57
  • 原文地址:https://www.cnblogs.com/NFii/p/12531963.html
Copyright © 2011-2022 走看看