zoukankan      html  css  js  c++  java
  • 【人生苦短,我学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))
     
  • 相关阅读:
    vfork与fork的区别
    常见的六种设计模式以及应用场景
    Java中常见的集合类比较
    排序——总结
    排序——交换排序
    排序——选择排序
    排序——归并排序
    排序——基数排序
    排序——插入排序
    设计模式
  • 原文地址:https://www.cnblogs.com/fwonfo/p/6636573.html
Copyright © 2011-2022 走看看