728x90
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:
"""
Do not return anything, modify s in-place instead.
"""
time = len(s)/2
count = 0
while time >= 1 :
time -= 1
temp = s[count]
s[count] = s[-(count+1)]
s[-(count+1)] = temp
count += 1
투포인터
2개의 포인터를 이용해 범위를 조절해가며 품.
문자열의 시작을 가리키는 left와 문자열의 끝을 가리키는 right를 선언.
left가 right보다 왼쪽에 있는 동안 left 위치의 내용과 right위치의 내용을 바꿈
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
reverse()
리스트에 제공되는 메소드로 문자열을 거꾸로 뒤집음.
list = [0,1,2,3]
list.reverse()
print(list)
# [3,2,1,0]
reversed()
리스트에 제공되는 메소드로 순서가 거꾸로 뒤집힌 리스트를 반환함
list = [0,1,2,3]
print(list.reversed())
# [3,2,1,0]
시간을 단축시키기 위해
1. 파이썬의 reverse이용
2. 리스트의 [::-1]이용
처음 생각했던 알고리즘의 문제점(틀린이유)
1. 슬라이싱 개념 부족
뒤에서 카운트 할 때 -1부터 시작하는 것을 몰랐음.
-1인거 알고 슬라이싱 할 때, -count+1을 해서 올바르게 수행이 안됬었음.
올바르게 수행하기 위해서 -(count+1)로 괄호를 씌워야만 했었음.
2. 끝까지 계산 안해서 while 조건문 횟수 틀림
728x90
'study > LeetCode' 카테고리의 다른 글
[Python] 15. Two Sum (0) | 2021.02.17 |
---|---|
[Python] 1. Two Sum (0) | 2021.01.22 |
[Python] 819. Most Common Word (0) | 2021.01.15 |
[Python] 937. Reorder Log Files (0) | 2021.01.15 |
[Python] 125. Valid Palindrome (0) | 2021.01.08 |