【人生苦短,我学Python】个人学习笔记——str.count方法

【人生苦短,我学Python】个人学习笔记——str.count方法

人生苦短,我学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))