[Algorithm] LeetCode #344 - Reverse String
개요
LeetCode #344, Reverse String 문제를 풀어봅니다.
Write a function that reverses a string. The input string is given as an array of characters s.
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 <= 105s[i]is a printable ascii character.
Follow up: Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
LeetCode는 Solution class 안에서 작동하게 만들어 놓아서 제시된 template 그대로 가져왔습니다. 그냥 reverse 함수를 쓰거나 하나씩 직접 손대면서 바꿔주거나 전체를 거꾸로 뒤집은 것으로 교체해 줄 수도 있습니다.
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
def reverseString_ver2(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left = 0
right = len(s)-1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
def reverseString_ver3(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
