代码随想录算法训练营第九天 | 151.翻转字符串里的单词 卡码网:55.右旋转字符串 28. 实现 strStr()

151.翻转字符串里的单词

怎么反转单词顺序?list.reverse().碰到空格,把单词加入list中。

class Solution:
    def reverseWords(self, s: str) -> str:
        s1 = []
        word = ''
        s += ' '
        for i in range(len(s)):
            if s[i] == ' ':
                if word != '':
                    s1.append(word)
                    word = ''
                else:
                    continue
            else:
                word += s[i]

        s1.reverse()
        return " ".join(s1)

但是你说有库不调是什么意思?

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.split()[::-1])

卡码网:55.右旋转字符串

这道题考的是怎么不引入额外空间,但是python的string不能修改,没办法了,人生苦短我用Python

k = int(input())
s = str(input())

s2 = s[-k:]+s[:-k]
print(s2)

28. 实现 strStr()

KMP,写一次错一次。原理还是好理解的。

class Solution:
    def getNext(self, next: list[int], s: str) -> None:
        j = 0
        next[0] = 0
        for i in range(1, len(s)):
            while j > 0 and s[i] != s[j]:
                j = next[j - 1]
            if s[i] == s[j]:
                j += 1
            next[i] = j
    
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle) == 0:
            return 0
        next = [0] * len(needle)
        self.getNext(next, needle)
        j = 0
        for i in range(len(haystack)):
            while j > 0 and haystack[i] != needle[j]:
                j = next[j - 1]
            if haystack[i] == needle[j]:
                j += 1
            if j == len(needle):
                return i - len(needle) + 1
        return -1

459.重复的子字符串

KMP的应用,算一下next数组就知道怎么回事了,如果是符合要求的字符串,next矩阵前几个为0,后面递增,所以len(s) - next[-1]对应重复子字符串的长度。

class Solution:
    def getNext(self, next: list, s: str) -> list:
        next[0] = 0
        j = 0
        for i in range(1, len(s)):
            while j > 0 and s[j] != s[i]:
                j = next[j - 1]
            if s[j] == s[i]:
                j += 1
            next[i] = j
    def repeatedSubstringPattern(self, s: str) -> bool:
        if len(s) == 0:
            return False
        next = [0] * len(s)
        j = 0
        self.getNext(next, s)
        if next[-1] != 0 and (len(s)%(len(s) - next[-1]) == 0):
            return True
        return False

但是简单题有简单题的做法,把这个字符串s拼接在一起s+s,掐头去尾后(s+s)[1:-1],这个s仍然是其中一部分

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return s in (s+s)[1:-1]

顺便复习下双指针,最近一周笔试面试改小论文累死了。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值