344. Reverse String

Easy

Problem:

Create a function that reverses a string. The function should take a character array as input and directly manipulate the list in-place, without returning any value.

Input: ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]

https://leetcode.com/problems/reverse-string/

What to learn:

  • reverse(): is only available for lists.

  • Slicing can be used across different data types, including both strings and lists.

Solutions:

In order to modify string in-place without returning anything, we can swap two characters by narrowing the scope down.

List

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):
            tmp = s[i]
            s[i] = s[len(s) - i - 1]
            s[len(s) - i - 1] = tmp

Two Pointers

This approach involves solving the problem by adjusting the range with the use of two pointers.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        left, right = 0, len(s) - 1
        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1

Pythonic way

1. reverse() function

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

2. slicing

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s[:] = s[::-1] # Trick

Last updated