성장중/알고리즘 인터뷰

파이썬 알고리즘 인터뷰 p.145 문자열 뒤집기

끄억 2021. 4. 30. 21:17
반응형

파이썬 알고리즘 인터뷰 p.145 문자열 뒤집기

leetcode 344번

leetcode.com/problems/reorder-data-in-log-files/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

문제: Write a function that reverses a string. The input string is given as an array of characters s.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
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

투포인터 방식의 풀이법입니다. 범위를 점점 조정해가면서 답을 찾는 것 입니다.

left와 right 포인트를 지정해놓습니다. right에 -1을 해준 이유는 그냥 len(s)를 하면 5이기 때문입니다.

while문을 돌면서 자리를 바꿔주고 하나씩 이동하고 바꿔주고 이런 형식입니다! 

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        s.reverse()

책에도 파이썬 다운 방식이라 나와있긴한데 그래도 드디어...혼자 문제를 풀어냈습니다. 기분은 좋은데....더 노력하겠습니다.

 

 

 

반응형