fwonfo

人生苦短,我学Python

终于开始在LeetCode上刷题了,也终于决定在这里记录学习笔记。

Better late than never. ;)


今天做的是《Haming Distance》。汉明距离,指的是2个等长字符串对比,对应位置字符不一致的个数。

既然输入是2个整数,抑或运算之后,找出位置为1的个数就可以了。

第一次想到的还是最笨的方法,遍历查找(62ms):

  1 class Solution(object):
  2     def hammingDistance(self, x, y):
  3         """
  4         :type x: int
  5         :type y: int
  6         :rtype: int
  7         """
  8         s = bin(x ^ y)
  9         slen = len(s)
 10         s_idx = 0
 11         ham_dis = 0
 12         while s_idx < slen:
 13             t_idx = s.find(\'1\', s_idx)
 14             if t_idx < 0:
 15                 break
 16             ham_dis += 1
 17             s_idx = t_idx + 1
 18         return ham_dis

 

点开Solutions,发现有一行解法,使用的是str内置的函数 str.count(substr),不由得感叹“居然还有这么方便的方法!”

  1 class Solution(object):
  2     def hammingDistance(self, x, y):
  3         """
  4         :type x: int
  5         :type y: int
  6         :rtype: int
  7         """
  8         return bin(x ^ y).count(\'1\')
 
count用法:
str.count(sub, start= 0,end=len(string))
 

分类:

技术点:

相关文章:

  • 2021-06-28
  • 2021-06-15
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-04-22
  • 2021-09-24
  • 2021-11-26
  • 2021-12-30
  • 2021-12-31
  • 2021-04-07
  • 2021-11-07
相关资源
相似解决方案