344.反转字符串
解题方法1:
python内置倒转
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# # method 1
s[:] = s[::-1]
return s
解题方法2:
双指针
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# method 2
left = 0
right = len(s) - 1
while left < right:
s[left],s[right] = s[right],s[left]
left += 1
right -= 1
return s
541. 反转字符串II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
# # method 1
# length = len(s)
# left = 0
# while left < length:
# right = left + k
# s = s[:left] + s[left:right][::-1] + s[right:]
# left += 2 * k
# return s
# method 2
lr = list(s)
for i in range(0,len(s),2*k):
lr[i:i+k] = lr[i:i+k][::-1]
return ''.join(lr)
剑指Offer 05.替换空格
解题方法1:
python内置库
class Solution:
def replaceSpace(self, s: str) -> str:
# # method 1
return '%20'.join(s.split(" "))
解题方法2:
(1)统计空格数量,记作count
(2)修改字符串长度, 在原来长度上加上 2*count
(3)倒序遍历修改:i
指向原字符串尾部元素, j
指向新字符串尾部元素
当s[i]不是空格时, 执行s[j] = s[i], j -= 1
当s[i] 为空格时,将字符串闭区间 [j-2, j] 的元素修改为 "%20" , j -= 3
每次遍历 i -= 1
(4)当 i < 0 时, 遍历结束
class Solution:
def replaceSpace(self, s: str) -> str:
# # method 1
# return '%20'.join(s.split(" "))
# method 2
lr = list(s)
count = s.count(" ")
lr.extend(" " * 2*count)
left = len(s) - 1
right = len(lr) - 1
for i in range(len(s) - 1,-1,-1):
if lr[left] != ' ':
lr[right] = lr[left]
right -= 1
if lr[left] == ' ':
lr[right] = '0'
lr[right-1] = '2'
lr[right-2] = '%'
right -= 3
left -= 1
return ''.join(lr)
151.翻转字符串里的单词
class Solution:
def reverseWords(self, s: str) -> str:
# # mthod 1
# return ' '.join(reversed(s.split()))
# # method 2
# s = s.strip()
# left = len(s) - 1
# right = len(s) - 1
# res = []
# while left >= 0:
# while left >= 0 and s[left] != ' ':
# left -= 1
# res.append(s[left+1:right+1])
# while s[left] == ' ':
# left -= 1
# right = left
# return ' '.join(res)
# method 3
s = s.strip()
word = []
res = collections.deque()
for left in range(len(s)):
if s[left] != ' ':
word.append(s[left])
if s[left] == ' ' and word:
res.appendleft(''.join(word))
word = []
res.appendleft(''.join(word))
return ' '.join(res)
剑指Offer58-II.左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[:n]