2019/10/13:汉明距离
题目链接:https://leetcode-cn.com/problems/hamming-distance/
感觉还是对位运算不是很熟吧,这题刚开始没看标签,想用双指针直接解,只要指针不相等,那么计数加一,但发现python用bin转换后的二进制还带有相关字母,比如bin(4) = 0b100,所以,下面是我的错误代码:
def hammingDistance(x,y):
a,b,count = len(bin(x)) - 1,len(bin(y)) - 1,0
str_x,str_y = str(bin(x)),str(bin(y))
while a > 0 and b > 0 :
n1 = int(str_x[a]) if a > 0 else 0
n2 = int(str_y[b]) if b > 0 else 0
if n1 != n2:
count += 1
a,b = a - 1,b - 1
return count
下面是我看题解里面有一些大佬用python一行解出来的代码:
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x^y).count('1')
2019/11/18:字符串解码
题目链接:https://leetcode-cn.com/problems/decode-string
这是栈分类中的第三题,开始的想法和题解中的一样,希望可以用暴力一个个去走读取与判断,当然效果也是有的,代码如下:
class Solution:
def decodeString(self, s: str) -> str:
stack, this_str,num = [], '', 0
for i in s:
if i.isdigit():num = num * 10 + int(i)
elif i.isalpha():this_str += i
elif i == '[':
stack.append((this_str,num))
this_str, num = '', 0
else: # i == ']'
last_str, this_num = stack.pop()
this_str = last_str + this_num * this_str
return this_str