二刷复习
反转字符串
原地反转字符串
这道题很神奇不让return anything, 所以我return s[::-1]失败了。只能这么反转一下
class Solution:
def reverseString(self, s: List[str]) -> None:
n = len(s)
i,j = 0,n-1
while i < j:
tmp = s[i]
s[i] = s[j]
s[j] = tmp
i += 1
j-=1
反转字符串2
反转字符串2
反转字符串函数可以自己写,再加一个切片的步长2k就行
class Solution:
def reverseStr(self, s: str, k: int) -> str:
n = len(s)
res = list(s)
for i in range(0, n, 2*k):
res[i:i+k] = reversed(res[i:i+k])
return ''.join(res)
class Solution:
def reverseStr(self, s: str, k: int) -> str:
n = len(s)
def reverse_str(s):
n = len(s)
l, r = 0, n-1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return s
res = list(s)
for i in range(0, n, 2*k):
res[i:i+k] = reverse_str(res[i:i+k])
return ''.join(res)
替换空格
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(' ', '%20')
翻转字符串里的单词
翻转字符串里的单词
做法两次翻转
细节1:split()函数不能写成split(’ '), 这样会保留中间的两个空格的情况;而不带参数中间有多少个空格都会被当成分割符
细节2:strip()函数直接去掉首尾空格
class Solution:
def reverseWords(self, s: str) -> str:
s = s[::-1]
new_s = s.split()
res = []
for i in new_s:
i = i[::-1]
res.append(i)
res += [' ']
return ''.join(res).strip()
左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
s1 = s[0:n]
s2 = s[n:]
return s2+s1
找出字符串第一个匹配项的下标(用kmp写的)
找出字符串第一个匹配项的下标
kmp思路详解在kmp总结
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
def getnext(needle):
next = [0] * len(needle)
j = 0 #前缀的末尾位置的index, j+1 就是相同前后缀的长度
for i in range(1, len(needle)): # i是后缀末尾的index,从1开始
while j > 0 and needle[j] != needle[i]:
j = next[j-1]
if needle[j] == needle[i]: j += 1
next[i] = j #此时无论是哪种情况,最长相同前后缀的长度都是j
return next
next = getnext(needle)
j = 0 #j是模式串的指针(needle的
for i in range(len(haystack)):
while j > 0 and needle[j] != haystack[i]: j = next[j-1]
if needle[j] == haystack[i]: j += 1
if j == len(needle):
return (i-len(needle)+1)
return -1
重复的子字符串
重复的子字符串
如果把两个自己加起来,如果说掐头去尾之后还能里面找到自己,就是重复的
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
s_ = s+s
return s in s_[1:n*2-1]