0344. Reverse String

0344. Reverse String#

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.

Examples#

Example 1:

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

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:#

1 <= s.length <= 105
s[i] is a printable ascii character.

Follow-up#

Analysis#

  • Use two pointer method to swap characters iteratively

Solution#

# Solution 1: two pinter O(n)
def reverseString(s):
    if len(s) <= 1:
        return s

    l, r = 0, len(s)-1
    while l < r:
        s[l], s[r] = s[r], s[l]
        l += 1
        r -= 1
    
    return s

# test
s = ["h","e","l","l","o"]
print(reverseString(s))

s = ["H","a","n","n","a","h"]
print(reverseString(s))
['o', 'l', 'l', 'e', 'h']
['h', 'a', 'n', 'n', 'a', 'H']
# a pythonic solution
# Solution 1: two pinter O(n)
def reverseString(s):
    return s[::-1]

# test
s = ["h","e","l","l","o"]
print(reverseString(s))

s = ["H","a","n","n","a","h"]
print(reverseString(s))
['o', 'l', 'l', 'e', 'h']
['h', 'a', 'n', 'n', 'a', 'H']