Reverse Words in a String III

I solved this easy LC problem in less than 10 seconds :D

class Solution {
    fun reverseWords(s: String): String = s.split(" ").map{it.reversed()}.joinToString(" ")
}
Runtime: 212 ms, faster than 100.00% of Kotlin online submissions for Reverse Words in a String III.
Memory Usage: 36.8 MB, less than 100.00% of Kotlin online submissions for Reverse Words in a String III.

Did you see how Kotlin makes our lives easier? But since I’m an engineer, I’ll write my own implementation of reverse function.

class Solution {
    fun reverseWords(s: String): String {
        val reverse: (String) -> String = {
            var chars = it.toCharArray()
            var left = 0
            var right = chars.size - 1
            while(left < right){
                val temp = chars[right]
                chars[right] = chars[left]
                chars[left] = temp
                left++
                right--
            }
            chars.joinToString("")
        }
        
        return s.split(" ").joinToString(" ", transform=reverse)
    }
}
Runtime: 264 ms, faster than 33.33% of Kotlin online submissions for Reverse Words in a String III.
Memory Usage: 38.2 MB, less than 100.00% of Kotlin online submissions for Reverse Words in a String III.

Kotlin’s reversed() function is definitely a lot faster. I wonder how did they implement the reversed() function.

comments powered by Disqus