LeetCode 344. Reverse String
Published in
Mar 14, 2021
題目:
不能用額外的空間反轉字符串。
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
思路:
- 以中間為軸心,左右互換,也就是第一位跟最後一位互換,依此類推,因此只需go over 一半長度
for i in range(len(s)//2): - s[i], s[-i-1] = s[-i-1], s[i]
Coding:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s)//2):
s[i], s[-i-1] = s[-i-1], s[i]