본문 바로가기
LeetCode/Two Pointers

[LeetCode][Kotlin] 557. Reverse Words in a String III

by jinwo_o 2024. 10. 19.

557. Reverse Words in a String III

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

문자열 s가 주어지면, 공백과 초기 단어 순서를 유지하면서 문장 내 각 단어의 문자 순서를 뒤집습니다.

 

Example 1:

Input: s = "Let's take LeetCode contest"

Output: "s'teL ekat edoCteeL tsetnoc"

 

Example 2:

Input: s = "Mr Ding"

Output: "rM gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 10^4
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

코드 1

class Solution {
    fun reverseWords(s: String): String {
        return s.split(" ").joinToString(" ") { it.reversed() }
    }
}

 

코드 2

class Solution {
    fun reverseWords(s: String): String {
        val charArray = s.toCharArray()
        var l = 0

        for (r in charArray.indices) {
            if (charArray[r] == ' ' || r == charArray.lastIndex) {
                var tempL = l
                var tempR = if (r == charArray.lastIndex) r else r - 1

                while (tempL < tempR) {
                    charArray[tempL] = charArray[tempR].also { charArray[tempR] = charArray[tempL] }
                    tempL++
                    tempR--
                }
                l = r + 1
            }
        }

        return charArray.joinToString("")
    }
}