문제링크
https://leetcode.com/problems/reverse-string/
Reverse String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
코드
풀이1
1
2
3
4
5
6
7
8
9
10
11
|
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s)-1
while left<=right:
s[left],s[right] = s[right],s[left]
left+=1
right-=1
|
cs |
풀이2 recursion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if (s):
self.helper(s,0)
def helper(self, s, level):
# end condition
if (len(s) == level):
return
temp = s[level]
self.helper(s,level+1)
s[-1-level] = temp
|
cs |

POINT
풀이1
left, right two pointers를 적용하여 switch하는 전형적인 reverse방식을 사용하였다.
제일 간단한 풀이는 s.reverse()이다. :)
풀이2
recursion을 이용한 풀이이다. 매 recursion마다 현재 level(index)이 가리키는 값을 temp에 저장하고 recursion depth 에 도달하면 그 값을 추가하는 방식이다.
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 557. Reverse Words in a String III (0) | 2022.03.03 |
---|---|
[LeetCode] 167. Two Sum II - Input Array Is Sorted (0) | 2022.03.02 |
[LeetCode] 283. Move Zeroes (0) | 2022.03.02 |
[LeetCode] 189. Rotate Array (0) | 2022.03.01 |
[LeetCode] 977. Squares of a Sorted Array (0) | 2022.03.01 |