본문 바로가기
Algorithm/LeetCode

LeetCode - Reverse String

by HaningYa 2020. 9. 3.
728x90

 

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 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"]


class Solution {
    func reverseString(_ s: inout [Character]) {
        helper(&s, 0)
    }
    func helper(_ s: inout [Character], _ index: Int ){
        
        if  s.count/2  <= index  {
            return
        }
       
        let tmp = s[index]
        s[index] = s[s.count-index-1]
        s[s.count-index-1] = tmp
        helper(&s, index+1)
    }
}

728x90

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode - Reverse Linked List 🤦🏻  (0) 2020.09.09
LeetCode - Swap Nodes in Pairs  (0) 2020.09.03
LeetCode - Largest Time for Given Digits  (0) 2020.09.01
LeetCode - Running Sum of 1d Array  (0) 2020.08.30
LeetCode - Detect Capital  (0) 2020.08.07

댓글