344_Reverse String
Input: "hello"
Output: "olleh"Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"Solution 1: two pointers
def reverseString(s):
"""
:type s: str
:rtype: str
"""
# convert to list
l = list(s)
# two pointer
i , j = 0, len(l)-1
# invert letters at symmetric places
while i < j :
l[i], l[j] = l[j], l[i]
i += 1
j -= 1
return "".join(l)
# simpler code
def reverseString(s):
"""
:type s: str
:rtype: str
"""
ls = list(s)
for i in range(len(ls)//2):
ls[i], ls[~i] = ls[~i], ls[i]
return "".join(ls)Solution 2: recursive
Last updated