151.翻转字符串里的单词
解法一:
class Solution:
def reverseWords(self, s: str) -> str:
# 移除前后空格
s = s.strip()
# 整个字符串反转
s = s[::-1]
# 单词反转
s = ' '.join(word[::-1] for word in s.split())
return s
解法二:双指针
class Solution:
def reverseWords(self, s: str) -> str:
words = 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)
总结:
解法一:整体思路是,先去掉空格,反转整个列表,然后在反转单词。
解法二:将字符串拆分成单词,转成列表,然后反转单词再转换成字符串
卡码网:55.右旋转字符串
解法一:
k = int(input())
s = input()
s = s[::-1]
s = s[0:k][::-1] + s[k:][::-1]
print(s)
解法二:
k = int(input())
s = input()
s = s[len(s)-k:] + s[:len(s)-k]
print(s)
总结:
解法一:先进行反转然后前k个和后面的部分分别再次反转。有种负负得正的感觉
解法二:将字符串后面的k个字符移到前面
28. 实现 strStr()
class Solution:
def getNext(self, next, s):
j = -1
next[0] = j
for i in range(1, len(s)):
while j >= 0 and s[i] != s[j+1]:
j = next[j]
if s[i] == s[j+1]:
j += 1
next[i] = j
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
next = [0] * len(needle)
self.getNext(next, needle)
j = -1
for i in range(len(haystack)):
while j >= 0 and haystack[i] != needle[j+1]:
j = next[j]
if haystack[i] == needle[j+1]:
j += 1
if j == len(needle) - 1:
return i - len(needle) + 1
return -1
总结:KMP算法挺难的,二刷再来看看吧。代码实现是前缀表减1的版本
459.重复的子字符串
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] != -1 and len(s) % (len(s) - (nxt[-1] + 1)) == 0:
return True
return False
def getNext(self, nxt, s):
nxt[0] = -1
j = -1
for i in range(1, len(s)):
while j >= 0 and s[i] != s[j+1]:
j = nxt[j]
if s[i] == s[j+1]:
j += 1
nxt[i] = j
return nxt
总结:这题是KMP算法的应用,二刷再来看看吧。代码实现也是前缀表减1的版本