151.反转字符串中的单词
os:没想到用python做反转功能这么方便 nums[::-1]可以将字符串完全反转。split()可以自动忽略所有多余的空格
class Solution:
def reverseWords(self, s: str) -> str:
s=s[::-1]
s=" ".join(word[::-1] for word in s.split())
return s
右旋字符串
k = int(input())
s = input()
#通过切片反转第一段和第二段字符串
#注意:python中字符串是不可变的,所以也需要额外空间
s = s[len(s)-k:] + s[:len(s)-k]
print(s)
28.找出字符串中第一个匹配项的下标
kmp算法实现步骤
- 处理特殊情况
- 如果needle是空字符,返回0
- 如果haystack比needle短,返回-1
- 构建next数组
- 初始化next[0]=-1
- 使用双指针来构建next数组
- 使用next数组进行匹配
- 初始化两个指针i和j分别遍历haystack和needle
- 根据匹配情况移动指针:
- 字符匹配,双指针都右移
- 不匹配,根据next数组回退
- 当j到达needle末尾时,表示找到匹配
- 找到匹配时返回返回起始下标;遍历完没找到则返回-1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# 边界情况处理
if not needle: # 空needle返回0
return 0
if len(haystack) < len(needle): # haystack比needle短不可能匹配
return -1
# 构建KMP的next数组(部分匹配表)
def build_next(pattern: str):
next = [0] * len(pattern)
next[0] = -1 # 初始化
i, j = 0, -1 # i主指针,j前缀指针
while i < len(pattern) - 1:
if j == -1 or pattern[i] == pattern[j]:
i += 1
j += 1
next[i] = j # 记录最长前后缀长度
else:
j = next[j] # 不匹配时回退j
return next
next = build_next(needle)
# 使用next数组进行匹配
i = j = 0 # i遍历haystack,j遍历needle
while i < len(haystack) and j < len(needle):
if j == -1 or haystack[i] == needle[j]:
# 当前字符匹配成功或需要从头开始匹配
i += 1
j += 1
else:
# 不匹配时根据next数组跳转
j = next[j]
# 判断匹配结果
return i - j if j == len(needle) else -1