Description

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:

💡 Hint 1:
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!

Submitted Code

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        front = 0
        back = len(s) - 1

        while front < back:
            s[front], s[back] = s[back], s[front]
            front += 1
            back -= 1

Runtime: 0 ms | Beats 100.00%
Memory: 19.86 MB | Beats 66.81%

Other Solutions

1st

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s.reverse()

time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)

내장 함수로 간단하게 구현 가능하다.

Leave a comment