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
풀이 과정
문자열 s를 뒤집는 문제이다.
크게 3가지 방법을 떠올릴 수 있다.
1. 내장 함수 사용
그냥 파이썬 내장 함수 써서 뒤집는 방법이다. s.reverse()를 사용하면 된다.
2. 투 포인터 사용
문자열의 시작과 끝에 포인터 2개를 두고 포인터의 인덱스에 해당하는 문자끼리 서로 바꿔가면서 왼쪽 포인터는 한칸 전진, 오른쪽 포인터는 한칸 후퇴하면서 계속 바꿔가면 된다. 이 방법대로 문제를 풀이하였다.
3. 문자열 슬라이싱
s = s[::-1]로 뒤집어서 할당해주면 될 것 같지만 문제에서 공간복잡도를 O(1)로 제한하였다. s[:] = s[::-1] 같은 트릭을 사용하여 이 방법으로도 문제를 해결 할 수 있다.
소스 코드
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 819. Most Common Word [Python] (0) | 2022.07.21 |
---|---|
LeetCode - 937. Reorder Data in Log Files [Python] (0) | 2022.07.21 |
LeetCode - 125. Valid Palindrome [Python] (0) | 2022.07.19 |
LeetCode - Trapping Rain Water [Python] (0) | 2022.07.07 |
LeetCode - Two Sum [Python] (0) | 2022.07.07 |