151.翻转字符串里的单词
大而化小,先有整体思路,再写局部函数
reverse用的很多
class Solution:
def reverse(self, s: List[str], start: int, end: int) -> None:
#[]
l = (end-start+1)//2
for i in range(0, l):
s[start+i], s[end-i] = s[end-i], s[start+i]
def removeExtraSpaces(self, s: List[str]) -> List[str]:
slow = 0
fast = 0
while fast<len(s):
# for fast in range(0, len(s)): #python的for只会按着顺序从头到尾一个一个来,如果中间改变了i的值,for还是会按照原来的顺序来
if s[fast] != ' ':
# add spaces before words except the first word
if slow != 0:
s[slow] = ' '
slow += 1
# add the word
while fast<len(s) and s[fast]!=' ':
s[slow] = s[fast]
slow += 1
fast += 1
else:
fast += 1
return s[:slow:]
def reverseWords(self, s: str) -> str:
s = list(s)
# reverse the sentence
self.reverse(s, 0, len(s)-1)
# remove extra spaces
s = self.removeExtraSpaces(s)
# reverse back every word
start = 0
for end in range(0, len(s)+1):
if end == len(s) or s[end] == ' ':# and/or连接前后大有文章:先判断i是否out of range,再判断s[i]是否是空格
self.reverse(s, start, end-1)
start = end + 1
return "".join(s)
卡码网:55.右旋转字符串
跟翻转单词一样,先转位置,再转正反(因为翻转的翻转是原来的正反)
class Solution:
def reverse(self, s: List[str], start: int, end: int) -> None:
#[]
l = (end-start+1)//2
for i in range(0,l):
s[start+i], s[end-i] = s[end-i], s[start+i]
def rightReverse(self, s:str, n: int) -> str:
s = list(s)
# 跟翻转单词一样,先转位置,再转正反(因为翻转的翻转是原来的正反)
# all reverse
self.reverse(s, 0, len(s)-1)
# reverse the first n digits
self.reverse(s, 0, n-1)
# reverse the last len(s)-n digits
self.reverse(s, n, len(s)-1)
return "".join(s)
双指针法
对数组、字符串的增、删很有用
链表:反转链表(三指针),找环
哈希表