[LeetCode 318] Maximum Product of Word Lengths(Python)
来源:互联网 发布:moe破解软件下载 编辑:程序博客网 时间:2024/06/06 12:30
题目描述
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”.Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.
思路
本题要找到数组中两个最长的且没有公共字母的字符串。如果有暴力解法,时间复杂度过高,而且代码也不简洁。因为每个字符串都是由26个字母组成的,所以我们可以考虑先对每个字符串编码,可以利用位运算进行编码,出现的字母对应位置一。然后判断两个字符串有没有公共字符只需判断它们对应的编码的与运算是否为1即可。
代码
class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ if words is None or len(words) <= 1: return 0 codes = [] for i in words: tmp = 0 for j in list(i): tmp |= 1 << (ord(j) - ord('a')) codes.append(tmp) res = 0 for i in range(len(codes)): for j in range(i + 1, len(codes)): if codes[i] & codes[j] == 0: res = max(res, len(words[i]) * len(words[j])) return res
复杂度分析
时间复杂度
- [LeetCode 318] Maximum Product of Word Lengths(Python)
- [LeetCode 318] Maximum Product of Word Lengths
- LeetCode 318: Maximum Product of Word Lengths
- LeetCode 318 Maximum Product of Word Lengths
- leetcode(318):Maximum Product of Word Lengths
- leetcode 318 Maximum Product of Word Lengths
- LeetCode 318 Maximum Product of Word Lengths
- LeetCode #318: Maximum Product of Word Lengths
- Leetcode 318 Maximum Product of Word Lengths
- LeetCode 318 Maximum Product of Word Lengths
- leetcode Maximum Product of Word Lengths
- Leetcode: Maximum Product of Word Lengths
- 【leetcode】318. Maximum Product of Word Lengths
- leetcode Maximum Product of Word Lengths
- leetcode -- Maximum Product of Word Lengths -- 重点
- Maximum Product of Word Lengths | LeetCode
- Leetcode: Maximum Product of Word Lengths
- LeetCode:Maximum Product of Word Lengths
- MySQL存储引擎--MyISAM与InnoDB区别
- BZOJ 1588 营业额统计 Splay
- lucene
- 【转载】10个最佳ES6特性
- Midland.Valley.Move.v2017.2.0.build.21565结构建模
- [LeetCode 318] Maximum Product of Word Lengths(Python)
- MonkeyDev
- HDU 6153 A Secret 扩展kmp
- C++11:std::function
- java多线程编程-volatile与synchronized之前的比较
- CentOS7网络配置
- android 部分驱动修改的编译指令
- QT5模块
- expdp/impdp (ORACLE 11.2.0.4)