Leetcode: Reverse string
Reverse a string and only use one extra variable. The solution is straightforward with two pointers, p1
and p2
. THe idea here is to start from both ends and increment p1
and decrement p2
until both of them meet in the middle. To switch the values of variables without assigning a temporary variable, the notation of a, b = b, a
can be used. To convert a string into a list of characters, surroung the string with [*s]
.
from typing import List, Optional
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
p1 = 0
p2 = len(s) - 1
while p1 < p2:
s[p1], s[p2] = s[p2], s[p1]
p1 += 1
p2 -= 1
if __name__ == '__main__':
s = Solution().reverseString
t = [*'Hello world']
print(s(t), t)
t = [*'AB']
print(s(t), t)