LeetCode 344. Reverse String

題目:

不能用額外的空間反轉字符串。

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"]

思路:

  1. 以中間為軸心,左右互換,也就是第一位跟最後一位互換,依此類推,因此只需go over 一半長度
    for i in range(len(s)//2):
  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]

--

--

Sharko Shen
Data Science & LeetCode for Kindergarten

Thinking “Data Science for Beginners” too hard for you? Check out “Data Science for Kindergarten” !