Algorithm/LEET CODE ( 파이썬 알고리즘 인터뷰)
[LEET CODE] 344. Reverse String
newnu
2021. 3. 4. 00:03
반응형
#Problem
Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters.
Example 1:
|
# My Answer
class Solution:
def reverseString(self, s):
front =0
end = len(s)-1
while front<end:
s[front],s[end] = s[end],s[front] # 바깥쪽부터 안쪽 방향으로 문자 바꾸기
front+=1
end-=1
return s
# Solution 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
#Solution 2 - 파이썬다운 방식 (파이썬의 기본 기능을 이용하여 한 줄로 풀이)
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
reverse() - 리스트에만 제공되는 함수
참고) reverse() / reversed() 함수 newnuleee.tistory.com/6
반응형