#67 Add Binary
Given two binary strings
a
andb
, return their sum as a binary string.
解题思路:
1. 考虑到 string A B 的长度可能不一样所以先补齐零。
2. 然后将string A和B 同一个index的数字求和之后赋予给新的string,new
3. 用for循环去从后往前看new每一个数位是不是大于2。逢二进一。
4.将new转变为string输出。
class Solution:
def addBinary(self, a: str, b: str) -> str:
# let string a and b have the same number of digits
if len(a) > len(b):
b = '0'*(len(a)-len(b)) + b
elif len(b) > len(a):
a = '0'*(len(b)-len(a)) + a
# create a new list to store the sum of int(a) and int(b)
new = [[] for _ in range(len(a))]
for i in range(len(a)-1, -1, -1):
new[i] = int(a[i]) + int(b[i])
# run through every digits of the list backwards
# add 1 to the previous digits whenever comes across 2 or above
for i in range(len(a)-1, -1, -1):
if new[i] >= 2:
new[i] -= 2
if i == 0:
new.insert(0, 1)
else:
new[i-1] += 1
res = ''
for i in new:
res += str(i)
return res
runtime:
emmm 已经出界了。学习一下其他人的思路。
有直接可以用的built-in function:bin()
补漏到一个知识盲点——int()有两种作用:
1) int(纯数字)是取整数的意思
2)int(字符串,进制base)求的是当字符串是base进制的数时,转换成十进制之后是多少
因为题目给的a,b字符串本身就是二进制的,所以20ms的这个思路等于是先求两个二进制字符串的十进制之和,然后再用bin()转换成二进制。之所以后面还跟个[2:],是因为bin(数字)本身输出的是0bXXX,【0b】代表这个数是二进制的意思。
重写一遍:
#28 Implement strStr()
Implement strStr().
Given two strings
needle
andhaystack
, return the index of the first occurrence ofneedle
inhaystack
, or-1
ifneedle
is not part ofhaystack
.Clarification:
What should we return when
needle
is an empty string? This is a great question to ask during an interview.For the purpose of this problem, we will return 0 when
needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
解题思路:
要把needle这个string拆成单个字母然后看在haystack是否按顺序对应吗?这样感觉会很麻烦。
或者循环haystack,然后对比[i:i+(len(needle))]与needle。有相等的就return i。没有就return -1。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
k = len(needle)
for i in range(len(haystack)):
if haystack[i:i+k] == needle:
return i
return -1
runtime:
看discussion,python还有个build-in的function可以直接用。haystack.find(needle)。没有找到返回-1,needle是空集的话,正好返回0.几乎是量身打造的function了。