Algorithm/LeetCode
LeetCode - Reverse String
HaningYa
2020. 9. 3. 20:02
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