字符串 | 151.翻转字符串里的单词 卡码网:55.右旋转字符串 28. 实现 strStr()

151.翻转字符串里的单词

题目链接: 151.翻转字符串里的单词 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:字符串复杂操作拿捏了! | LeetCode:151.翻转字符串里的单词

思路

  1. 去除开头和结尾的空格,确定一个单词的边界并将其添加至单词列表

双指针

class Solution:
    def reverseWords(self, s: str) -> str:
        n = len(s)
        left = 0
        right = n-1
        # 去除开头和结尾的空格
        while left<right and s[left] == ' ':
            left = left+1
        while left<right and s[right] == ' ':
            right = right-1
        
        res = []
        r,l = right,right
        while l >= left:
            while l > left and s[l-1] != ' ':
                l = l-1
            res.append(s[l:r+1])
            l = l-1
            while s[l] == ' ':# 跳过单词间空格
                l = l-1
            r = l
        res = ' '.join(res)
        return res

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

题目链接: 卡码网:55.右旋转字符串
文章讲解:代码随想录

思路

  1. 我用的是python,所以解法比较简单

方法

class Solution:
    def rotate(self,s,k):
        l = len(s)-1
        r = l - int(k) + 1
        new_s = s[r:l+1] + s[:r]
        return new_s

sol = Solution()
k = input()
s = input()
res = sol.rotate(s,k)
print(res)

28. 实现 strStr()

题目链接: 28. 实现 strStr() - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:帮你把KMP算法学个通透!(理论篇)

思路

  1. 暴力解
  2. KMP算法【没学懂,代码写不出来】,459. 重复的子字符串 是进阶,也写不出来

暴力解

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        for i in range(len(haystack)):
            if haystack[i:i+n] == needle:
                return i

        return -1

KMP算法

class Solution:
    def getNext(self,next,s):
        j = 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:
        n = len(needle)
        next = [0]*n
        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 needle[j] == haystack[i]:
                j += 1
            if j == n: # 遍历完needle,说明匹配
                return i - n + 1
        return -1
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值