본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode 344. Reverse String [Easy]

by 벤진[Benzene] 2020. 5. 20.

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

Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]

 

-문제해결 정리-

1. input 리스트의 중간지점까지 돌면서 첫번째와 끝쪽의 값을 계속해서 Swap 해준다.

2. 중간지점까지 오면 loop을 끝내고 함수종료

 

속도와 메모리 효율이 생각보다 좋지는 않다.

Soultion을 보니 .reverse() 함수로도 한줄만에 풀수있다.

 

-Another way to solve with two pointer-

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

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

https://leetcode.com/

'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글

LeetCode 48. Rotate Image  (0) 2020.05.22
LeetCode 283. Move Zeroes  (0) 2020.05.22
LeetCode 189. Rotate Array  (0) 2020.05.22
LeetCode 01. Two Sum  (0) 2020.05.21
LeetCode 36. Valid Sudoku [Medium]  (2) 2020.05.20

댓글