LeetCode刷题总结(持续更新中。。。)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jin_tmac/article/details/79991052
1、回文字符

返回字符串是否回文结构

def huiwen(str):

    if len(str) == 1:
        return True

    elif len(str) == 2:
        return str[0]==str [-1]

    else:
        return str[0]==str [-1] and huiwen(str[1:-1])
2、宝石与石头

return sum(map(S.count, J))

3、汉明距离

用异或运算
return bin(x ^ y).count(‘1’)
注:按位异或运算符:当两对应的二进位相异时,结果为1
自己的做法:silly~–_–

  def hammingDistance(self, x, y):
      """
      :type x: int
      :type y: int
      :rtype: int
      """

      sum0 = 0
      x_bin = bin(x)[2:]
      y_bin = bin(y)[2:]

      b_x = 4*(1+len(x_bin)//4) if len(x_bin)%4 != 0 else 4*(len(x_bin)//4)
      b_y = 4*(1+len(y_bin)//4) if len(y_bin)%4 != 0 else 4*(len(y_bin)//4)

      b = max(b_x, b_y)

      x_bin1 = x_bin.zfill(b)[::-1]
      y_bin1 = y_bin.zfill(b)[::-1]

      for i in range(b):
          if x_bin1[i] == y_bin1[i]:
              sum0 += 1

      return b - sum0        

猜你喜欢

转载自blog.csdn.net/jin_tmac/article/details/79991052