151.翻转字符串里的单词
题目链接: 151.翻转字符串里的单词 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:字符串复杂操作拿捏了! | LeetCode:151.翻转字符串里的单词
思路
- 去除开头和结尾的空格,确定一个单词的边界并将其添加至单词列表
双指针
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.右旋转字符串
文章讲解:代码随想录
思路
- 我用的是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算法学个通透!(理论篇)
思路
- 暴力解
- 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
755

被折叠的 条评论
为什么被折叠?



