알고리즘/해결

LeetCode557. Reverse Words in a String III

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

1. 문제(원본)

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

2. 문제

입력된 문자열을 스페이스를 간격으로 역순하여 출력하라

3. 나의 답

class Solution {

    func reverseWords(_ s: String) -> String {

        var result = ""

        let splitArray = s.split(separator: " ")

        for element in 0..<splitArray.count {

            result = result.count == 0 ? result + splitArray[element].reversed() : result + " " + splitArray[element].reversed()

        }

        let te = result == "s'teL ekat edoCteeL tsetnoc"

        print(te)

        return result

    }

}

4. 다른 유저의 답

#1

func reverseWords(_ s: String) -> String {

    var output = ""

    let words = s.split(separator: " ")

    for (index, word) in words.enumerated() {

        var reversedWord = String(word.reversed())

        if index != words.count-1 {

            reversedWord += " "

        }

        output.insert(contentsOf: reversedWord, at: output.endIndex)

    }

    return output

}

5. 마무리

문자열을 역순으로 출력하는 문제는 많이 접해본 문제이기 때문에 큰 어려움 없이 풀 수 있었다.

728x90

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

LeetCode1046. Last Stone Weight  (0) 2020.04.05
LeetCode344. Reverse String  (0) 2020.03.31
LeetCode942. DI String Match  (0) 2020.03.25
LeetCode561. Array Partition I  (0) 2020.03.25
LeetCode1051. Height Checker  (0) 2020.03.25