DEV Community

Cover image for Reverse String | LeetCode | Python
Retiago Drago
Retiago Drago

Posted on • Updated on

Reverse String | LeetCode | Python

The Problem

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.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ascii character.

The Input

Sample:

s = ["h","e","l","l","o"]
Enter fullscreen mode Exit fullscreen mode

The Output

Sample:

["o","l","l","e","h"]
Enter fullscreen mode Exit fullscreen mode

Explanation

Already cleared.

The Solution

Pay attention to what in-place algorithm means. One simple solution to do it is swapping both place the former and the latter index of the array until it meets in the middle.

The Code

Source Code 1

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l = len(s)
        for i in range(l//2):
            s[i], s[l-1-i] = s[l-1-i], s[i]
Enter fullscreen mode Exit fullscreen mode

code 1 result

Source Code 2

The same as the previous one but it will only swap if they have not identical values. Hence, it will less swapping and assignment than before.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l = len(s)
        for i in range(l//2):
            if s[i] != s[l-1-i]:
                s[i], s[l-1-i] = s[l-1-i], s[i]
Enter fullscreen mode Exit fullscreen mode

code 2 result

Original Source

Let's be friend 👋

Top comments (0)