-
Notifications
You must be signed in to change notification settings - Fork 26
/
Reverse-Words-in-a-String.kt
45 lines (43 loc) · 1.26 KB
/
Reverse-Words-in-a-String.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package string_integer
class ReverseWordsinaStringKotlin151 {
fun reverseWords(s: String): String =
s.trim()
.split("\\s+".toRegex())
.reversed()
.joinToString(separator = " ")
/*
fun reverseWords(s: String): String {
val list: MutableList<String> = LinkedList()
var index = 0
while (index < s.length) {
if (s[index] == ' ') {
++index
} else {
val stringBuilder = StringBuilder()
while (index < s.length && s[index] != ' ') {
stringBuilder.append(s[index])
++index
}
list.add(stringBuilder.toString())
}
}
val result = StringBuilder()
for (i in list.size - 1 downTo 0) {
result.append(list[i])
if (i != 0){
result.append(" ")
}
}
return result.toString()
}
*/
}
fun main() {
val solution = ReverseWordsinaString151()
// blue is sky the
println(solution.reverseWords("the sky is blue"))
// world! hello
println(solution.reverseWords(" hello world! "))
// example good a
println(solution.reverseWords("a good example"))
}