ZhongKuo0228 / study

0 stars 0 forks source link

344. Reverse String #43

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

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

Constraints:

1 <= s.length <= 105 s[i] is a printable ascii character.

fockspaces commented 1 year ago

這裡不能直接 s = s[::-1],因為要直接 in-place modify 上面會 new 新的 object,之後讓 s 指向新的 object 原來指向的 object 並不會被修改 這邊直接 two-pointer 來改即可

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, right = left + 1, right - 1