Leetcode日练笔记24 #67 #28 Add Binary & Implement strStr()

本文记录了LeetCode中两道题目的解题思路,分别是#67 Add Binary,通过补零、逐位相加并处理进位的方法解决二进制字符串相加问题;以及#28 Implement strStr(),讨论了如何查找字符串的首次出现位置,介绍了Python内置的find()函数来简化问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#67 Add Binary

Given two binary strings a and b, 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 and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

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了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值