Always Be Wise

문자열 조작 : 문자열 뒤집기(리트코드 344번) 본문

알고리즘/리트코드

문자열 조작 : 문자열 뒤집기(리트코드 344번)

bewisesh91 2021. 12. 14. 21:24
728x90

▶ 문제 : 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

##### 문제 #####
문자열을 뒤집는 함수를 작성하라. 입력값은 문자 배열이며, 리턴 없이 리스트 내부를 직접 조작하라.

##### 입력 #####
["h", "e", "l", "l", "o"]

##### 출력 #####
["o", "l", "l", "e", "h"]

 

▶ 접근 방법

투 포인터를 이용하여 자리를 바꾸는 방법, 파이썬 내장 함수를 이용하는 방법을 사용하였다.

 

▶ 풀이 코드

from typing import List


ex_list = ["h", "e", "l", "l", "o"]

def reverse_string(list: List[str]) -> None:
    left, right = 0, len(list) -1
    while left < right:
        list[left], list[right] = list[right], list[left]
        left += 1
        right -= 1

reverse_string(ex_list)
print(ex_list)

ex_list.reverse()
print(ex_list)

 

▶ 관련 링크

2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 유효한 팰린드롬(리트코드 125번)