iOS/코딩테스트

백준 9093 단어뒤집기(swift)

개발자 Leo 2022. 8. 23. 23:31

 

String을 쪼개서 뒤집는 문제였습니다.

String의 reversed() 함수를 활용해서 풀어보았습니다.

 

let T = Int(readLine()!) // 테스트 케이스의 수

for _ in 0..<T! {
    receiveStrings()
}

func receiveStrings() {
    let input = readLine()!.split(separator: " ").map(){ String($0) }
    var result = ""
    for i in 0..<input.count {
        result.append(String(input[i].reversed()))
        result.append(" ")
    }
    print(result)
}

 

reversed()의 관련 설명입니다.

    /// You can reverse a collection without allocating new space for its
    /// elements by calling this `reversed()` method. A `ReversedCollection`
    /// instance wraps an underlying collection and provides access to its
    /// elements in reverse order. This example prints the characters of a
    /// string in reverse order:
    ///
    ///     let word = "Backwards"
    ///     for char in word.reversed() {
    ///         print(char, terminator: "")
    ///     }
    ///     // Prints "sdrawkcaB"
    ///
    /// If you need a reversed collection of the same type, you may be able to
    /// use the collection's sequence-based or collection-based initializer. For
    /// example, to get the reversed version of a string, reverse its
    /// characters and initialize a new `String` instance from the result.
    ///
    ///     let reversedWord = String(word.reversed())
    ///     print(reversedWord)
    ///     // Prints "sdrawkcaB"
    ///
    /// - Complexity: O(1)
    @inlinable public func reversed() -> ReversedCollection<String>

    /// Returns an array containing the results of mapping the given closure
    /// over the sequence's elements.
    ///
    /// In this example, `map` is used first to convert the names in the array
    /// to lowercase strings and then to count their characters.
    ///
    ///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    ///     let lowercaseNames = cast.map { $0.lowercased() }
    ///     // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
    ///     let letterCounts = cast.map { $0.count }
    ///     // 'letterCounts' == [6, 6, 3, 4]
    ///
    /// - Parameter transform: A mapping closure. `transform` accepts an
    ///   element of this sequence as its parameter and returns a transformed
    ///   value of the same or of a different type.
    /// - Returns: An array containing the transformed elements of this
    ///   sequence.
    ///
    /// - Complexity: O(*n*), where *n* is the length of the sequence.

'iOS > 코딩테스트' 카테고리의 다른 글

백준 9012 (swift)  (0) 2022.08.25
백준 10828번 스택(swift)  (1) 2022.08.22
백준 온라인 추천 문제  (0) 2022.08.22