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"]
The Output
Sample:
["o","l","l","e","h"]
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]
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]
Top comments (0)