小伙伴们共勉~
解题思路:双指针解法,直接把两边调转
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s)-1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -=1
解题思路:reversed
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = reversed(s)
541. 反转字符串 II
解题思路:灵活应用左右指针,每次loop的step = 2*k步。同时把str改为list更好替换
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverse_substring(text):
left, right = 0, len(text)-1
while left<right:
text[left], text[right] = text[right], text[left]
left+=1
right-=1
return text
res = list(s)
for char in range(0, len(s), 2*k):
res[char: char+k] = reverse_substring(res[char: char+k])
return ''.join(res)
解题思路:reverse可以直接用text[::-1]。 定义需要reverse和keep的部分,累加到res
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverse_substring(text):
return text[::-1] # 使用切片来反转字符串
res = ""
# 按照每段 2*k 的长度进行遍历
for i in range(0, len(s), 2 * k):
# 对于每一段,前 k 个字符反转,后面的保持不变
res += reverse_substring(s[i:i + k]) + s[i + k:i + 2 * k]
return res
卡码网:54.替换数字
解题思路:python解法好像没那么多弯弯绕绕
class Solution:
def change(self, s: str) -> str:
res = ""
for char in s:
if char.isdigit():
res += "number" # 拼接 "number"
else:
res += char
return res
更简单一点的写法
class Solution:
def change(self, s: str) -> str:
return ''.join("number" if char.isdigit() else char for char in s)