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))
     
  • 相关阅读:
    Diocp截图
    [DIOCP视频]-DIOCPFileServer视频
    DIOCP 运作核心探密
    DIOCP-DIOCPv5的处理能力
    【被C折腾系列】用C调DIOCP编码客户端通信
    DIOCP-V5发布
    MyBean通用报表插件介绍
    Amazon
    输出所有大小写字符的组合
    删除最少字符生成Palindrome
  • 原文地址:https://www.cnblogs.com/fwonfo/p/6636573.html
Copyright © 2011-2022 走看看