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.
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
class Solution:
def reverseString(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
Time Complexity:
Space Complexity:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:]=s[::-1]
🔴 공간 복잡도가 로 제한되어 있으므로 s=s[::-1]
은 통과되지 않는다.
s[:]=s[::-1]
랑 s=s[::-1]
가 어떻게 다른데?
s = s[::-1]
creates a new local variables
and assigns the reversed list to it, it doesn't modify the lists
, whereass[:] = s[::-1]
creates an intermediate reversed list, and assigns it back tos
, since we are using slice notations[:]
.
References
- https://leetcode.com/problems/reverse-string/
- https://leetcode.com/problems/reverse-string/discuss/80946/Python2.7-(3-solutions%3A-Recursive-Classic-Pythonic)
- 파이썬 알고리즘 인터뷰(95가지 알고리즘 문제 풀이로 완성하는 코딩 테스트), 박상길 지음