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:
Input: [“abcw”,”baz”,”foo”,”bar”,”xtfn”,”abcdef”]
Output: 16
Explanation: The two words can be “abcw”, “xtfn”.
Example 2:
Input: [“a”,”ab”,”abc”,”d”,”cd”,”bcd”,”abcd”]
Output: 4
Explanation: The two words can be “ab”, “cd”.
Example 3:
Input: [“a”,”aa”,”aaa”,”aaaa”]
Output: 0
Explanation: No such pair of words.
题意分析:
在列表中找两个字符串使得这两个字符串的长度乘积最大,这两个字符串必须满足没有相同字符。
算乘积一个n^2即可,关键在于限制条件,我们固然可以用set来记录字符串然后用 &操作符判断,但是就有点小蠢,空间也相对花费较大
因为只有26个英文字母,我们完全可以用26位长的数字来表示,1代表有,0代表没有,&操作也方便
这种用数字表示字母的思想是一种很经典的思路,已经不止见到过一次了,得记住!
思路:
用一个数组记录长度,用一个数组记录位表示,n^2复杂度解决
1 | class Solution(object): |