알고리즘/해결

LeetCode344. Reverse String

언클린 2020. 3. 31. 20:50
728x90

1. 문제(원본)

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

2. 문제

입력받은 문자 배열을 역순으로 정렬시켜라

3. 나의 답

class Solution {

    func reverseString(_ s: inout [Character]) {

        //   s = s.reversed() -> 간단하지만 문제의 의도가 아니기 때문에 주석 처리

        var temp: Character

        for element in 0..<(s.count / 2) {

            temp = s[element]

            s[element] = s[s.count - 1 - element]

            s[s.count - 1 - element] = temp

        }

    }

}

4. 다른 유저의 답

#1

class Solution {

    func reverseString(_ s: inout [Character]) {

        var len = s.count

 

        for i in 0..<len/2 {

            var temp = s[i]

            s[i] = s[len-1-i]

            s[len-1-i] = temp

        }

    }

}

5. 마무리

이번 문제는 swift에서 제공하는 함수를 사용하면 바로 풀리지만 문제자의 의도가 아니기 때문에 그냥 간단히 스왑처리고 풀어보았다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode867. Transpose Matrix  (0) 2020.04.05
LeetCode1046. Last Stone Weight  (0) 2020.04.05
LeetCode557. Reverse Words in a String III  (0) 2020.03.31
LeetCode942. DI String Match  (0) 2020.03.25
LeetCode561. Array Partition I  (0) 2020.03.25