leetcode_318. Maximum Product of Word Lengths 求两个不相交的字符串的长度乘积的最大值,将字母转换成二进制形式,按位与比较是否有相同字母

来源:互联网 发布:office2011 mac免激活 编辑:程序博客网 时间:2024/06/10 21: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.


题意:

给定一组字符串,求这些字符串中没有公共字符的两个字符串的乘积,返回乘积的最大值


代码:

class Solution(object):
    def maxProduct(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        
        n = len(words)
        
        if n < 1:
            return 0
        else :
            word_num = []          #将字符串转换成数字,便于后面的按位运算。一共有26个小写字母,假设有一个26位的二进制串,其中二进制串从低位到高位,依次代表每一个字母,如果字母在字符串中出现,则对应的位置设为1,否则,该位设为0
            for i in range(n) :           #遍历每个字符串
                temp = 0
                for j in range(len(words[i])) :         #遍历每个字符串的每一个字母
                    temp |= 1 << ord(words[i][j]) - ord('a')               #ord(words[i][j]) - ord('a'),得到字母相对于a的相对位置,然后通过右移符号<<,将1移到该字母对应的位置上。|= 按位或操作,就是只要有一个1就是1,两个都是0才是0。将该字符串之前的二进制串与当前的字母的二进制串进行按位或操作,得到新的二进制串
                word_num.append(temp)         #将该字符串对应的二进制串存入word_num中,是以十进制形式存进去的
            
            res = 0
            for i in range(n) :
                for j in range(i+1,n) :     #遍历任意两个字符串
                    if word_num[i] & word_num[j] == 0 :              #如果两个字符串对应的二进制串只要有相同的字母,则对应位置就都为1,执行按位与操作,结果就不会为0。故只要两个字符串的二进制串按位与结果为0,则这两个字符串一定没有共同的字母。
                        if len(words[i]) * len(words[j]) > res :
                            res = len(words[i]) * len(words[j])          #更新长度的乘积
            
            return res


笔记:

这个题在比较两个字符串是否有共同字母的时候,想了很久,参考了网上的方法。http://www.jianshu.com/p/8f97e63d1c1b

0 0