Python解LeetCode 771: Jewels and Stones

tech2022-07-16  181

给定A字符串,寻找B字符串中有多少字符出现在A中,重复出现的计算次数,拟采用位操作,为两个字符串计算位表示,然后让这两个位表示求与操作,将结果的二进制表示中各个位相加,或者说计算其中有几个数字1。关于字符串的位操作参见Python解LeetCode 318: Maximum Product of Word Lengths,解答代码如下:

import string class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ # 预计算每个字母的二进制表示 char_bin_dic = {} for char in list(string.ascii_lowercase + string.ascii_uppercase): offset = ord(char) - ord('A') char_bin_dic[char] = (1 << offset) J_bin = 0 for char in J: char_bin = char_bin_dic[char] J_bin = J_bin | char_bin # 二进制与运算计数 result = 0 for char in S: char_bin = char_bin_dic[char] if J_bin & char_bin != 0: result += 1 return result
最新回复(0)