Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: s = [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]
https://leetcode.cn/problems/reverse-string/solutions/2376290/ji-chong-bu-tong-de-xie-fa-pythonjavacgo-9trb/
思路一:快慢指针
class Solution:
def reverseString(self, s: List[str]) -> None:
left = 0
right = len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
思路二:循环
class Solution:
def reverseString(self, s: List[str]) -> None:
for i in range(len(s) // 2):
s[i], s[-i - 1] = s[-i - 1], s[i]
思路三:使用语法糖
class Solution:
def reverseString(self, s: List[str]) -> None:
# s[:] = s[::-1] 是切片赋值语法,表示用 s[::-1] 替换 s 中的元素。
# 注意不能写成 s = s[::-1],因为 s 只是形参,修改 s 不会影响函数外部传入的实参。
# 注意这不是原地操作,需要 O(n) 额外空间。
s[:] = s[::-1]