程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Leetcode brush questions Python] 318. Maximum word length product

編輯:Python

1 題目

給你一個字符串數組 words ,找出並返回 length(words[i]) * length(words[j]) 的最大值,並且這兩個單詞不含有公共字母.如果不存在這樣的兩個單詞,返回 0 .

示例 1:

輸入:words = [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
輸出:16
解釋:這兩個單詞為 “abcw”, “xtfn”.

示例 2:

輸入:words = [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
輸出:4
解釋:這兩個單詞為 “ab”, “cd”.

2 解析

Use a number to refer to a string of letters:低 26 way to refer to letters a-z 是否出現過.The specific use is to convert each letter into bits,Then all the letter bits of the entire string are ANDed,Get a unique number to represent the current string.

Check whether the letters of two strings have the same letter,進行與運算,如果等於0,Descriptions do not have identical letters.Then judge the result of multiplying the lengths of the two strings,選出最大的即可.

時間復雜度 O ( n 2 ) O(n^2) O(n2)

3 Python實現

class Solution:
def maxProduct(self, words: List[str]) -> int:
masks = []
for word in words:
t = 0
for w in word:
u = 1 << (ord(w) - ord('a'))
t |= u
masks.append(t)
ans = 0
for i in range(len(words)):
for j in range(i):
if (masks[i] & masks[j]) == 0:
ans = max(ans, len(words[i]) * len(words[j]))
return ans

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved