最简洁的做法:s.strip().split()[::-1]
class Solution:
def reverseWords(self, s: str) -> str:
words = list(s.split())
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
return ' '.join(words)
最简洁的写法:s[-k:] + s[:-k]
k = int(input())
s = input()
n = len(s)
s1 = s[n-k:]
s2 = s[:n-k]
s_new = s1 + s2
print(''.join(s_new))
1. Python 的字符串类自带find方法,它能高效地找到子串的第一个匹配项的下标。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
left, right = 0, len(needle)
while right <= len(haystack):
if haystack[left:right] == needle:
return left
else:
left += 1
right += 1
return -1
2. KMP算法
def find_substring(haystack: str, needle: str) -> int:
def build_lps(pattern: str) -> list:
"""构建部分匹配表(Longest Prefix Suffix 表)"""
lps = [0] * len(pattern)
length = 0 # 当前最长前缀后缀长度
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length > 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
if not needle:
return 0
lps = build_lps(needle)
i = j = 0 # i 为 haystack 的索引,j 为 needle 的索引
while i < len(haystack):
if haystack[i] == needle[j]:
i += 1
j += 1
if j == len(needle): # 完全匹配
return i - j
else:
if j > 0:
j = lps[j - 1] # 利用 LPS 跳过不必要的字符
else:
i += 1
return -1
# 示例
haystack = "hello"
needle = "ll"
result = find_substring(haystack, needle)
print(result) # 输出: 2
如果最长前后缀长度能够整除字符串长度,说明字符串可以由重复子串构成。
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
lps = [0] * len(s)
length = 0
i = 1
while i < len(s):
if s[i] == s[length]:
length += 1
lps[i] = length
i += 1
else:
if length > 0:
length = lps[length-1]
else:
lps[i] = 0
i += 1
longest_prefix_suffix = lps[-1]
if longest_prefix_suffix > 0 and len(s) % (len(s) - longest_prefix_suffix) == 0:
return True
else:
return False