<LeetCode 문제>
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
리스트를 뒤집는 문제입니다. 이때, 리턴 없이 주어지는 리스트 내부를 직접 조작해야 합니다.
<풀이>
맨 처음 시도한 코드는 다음과 같습니다.
class Solution:
def reverseString(self, s: List[str]) -> None:
s=s[::-1]
기존 리스트가 뒤집힌 리스트의 data가 s에 들어있는 것은 맞지만, 기존 객체가 아닌 새로운 객체가 할당됩니다.
s=['h','e','l','l','o']
print(id(s))
s = s[::-1]
print(id(s))
#출력
#140538954467520
#140538954467456
이때 s가 아닌 s[:]에 할당하면 같은 객체에서 내용이 바뀝니다.
s=['h','e','l','l','o']
print(id(s))
s[:] = s[::-1]
print(id(s))
#출력
#140054522812352
#140054522812352
이 문제는 특이하게 공간복잡도를 O(1)로 제한해서 s=s[::-1]이 아닌 s[:]=s[::-1]로 할당해야 정답 처리됩니다.
슬라이싱이 아닌 리스트에 제공되는 reverse() 함수를 이용하여 문제를 풀 수도 있습니다.
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
추가로 투 포인터를 이용한 전통적인 방식으로 풀이할 수도 있습니다.
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
투 포인터와 비슷하게 풀이한 저의 방식은 다음과 같습니다.
class Solution:
def reverseString(self, s: List[str]) -> None:
for i in range(0,len(s)//2):
s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] #교환
<학습내용>
1. s[:] = s[::-1]은 같은 객체에서 내용이 바뀌고, s=s[::-1]은 새로운 객체가 할당
<학습이 필요한 내용>
1. reverse와 reversed의 차이(https://itholic.github.io/python-reverse-reversed/)
https://github.com/HoYoungChun/Algorithm_PS/blob/master/String/LC_344.py
GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers problem solving by Python, C++
Baekjoon Online Judge, Programmers problem solving by Python, C++ - GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers problem solving by Python, C++
github.com
'Algorithm > 파이썬 알고리즘 인터뷰 스터디' 카테고리의 다른 글
[문자열 조작] 06 가장 긴 팰린드롬 부분 문자열(Longest Palindromic Substring) ✔ (0) | 2021.07.29 |
---|---|
[문자열 조작] 05 그룹 애너그램(Group Anagrams) (0) | 2021.07.29 |
[문자열 조작] 04 가장 흔한 단어(Most Common Word) (0) | 2021.07.28 |
[문자열 조작] 03 로그 파일 재정렬(Reorder Data in Log Files) (0) | 2021.07.28 |
[문자열 조작] 01 유효한 팰린드롬(Valid Palindrome) (0) | 2021.07.27 |