leetcode151 翻转字符串中的单词
不适用split库函数:
class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
res = []
l, r = len(s) - 1,len(s) - 1
while l >= 0:
while l >= 0 and s[l] != ' ':
l -= 1
res.append(s[l + 1:r + 1])
while l >= 0 and s[l] == ' ':
l -= 1
r = l
return ' '.join(res)
使用split库函数:
class Solution:
def reverseWords(self, s: str) -> str:
s = s[::-1]
return ' '.join(i[::-1] for i in s.split())
卡码网 55 右旋字符串
k = int(input())
s = input()
print(s[-k:] + s[:-k])
leetcode28 找出字符串中第一个匹配项的下标
kmp算法入门
首先要明白什么是子串,比如aabaaf 的子串是a、aa、aab、aaba、aabaa、aabaaf
其次寻找最长相等前后缀,即get_next数组。
class Solution:
# 核心技术得到next数组
def get_next(self, s):
j, prefix = 0, [0]*len(s)
for i in range(1, len(s)):
while j > 0 and s[j] != s[i]:
j = prefix[j - 1]
if s[j] == s[i]:
j += 1
prefix[i] = j
return prefix
def strStr(self, haystack: str, needle: str):
j, prefix = 0, self.get_next(needle)
for i in range(len(haystack)):
while j > 0 and haystack[i] != needle[j]:
j = prefix[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - j + 1
return -1
leetcode 459 重复的子字符串
思路:如果字符串s 在s+s[1:-1]中可以找到,那么它由子串构成
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
if s in (s + s)[1:-1]:
return True
else:
return False
kmp算法思路:如果由重复的子字符串构成,则len(s)- next[-1]可以被len(s)整除且next[-1]不为0
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
if len(s) == 0:
return False
nxt = [0] * len(s)
self.getNext(nxt, s)
if nxt[-1] != 0 and len(s) % (len(s) - nxt[-1]) == 0:
return True
return False
def getNext(self, nxt, s):
nxt[0] = 0
j = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = nxt[j - 1]
if s[i] == s[j]:
j += 1
nxt[i] = j
return nxt