/**
* 翻转指定字符串中的内容, 每个单词以空格字符分开
*
* input:"the sky is blue"
*
* output: "blue is sky the"
*/
fun reversStringByCollection(s: String): String {
// 分割
val str: MutableList<String> = s.split("\\s+".toRegex()) as MutableList<String>
// 翻转
str.reverse()
// 插入
return str.joinToString(separator = " ")
}
fun reversStringByPointer(s: String): String {
// 定义左右指针,右指针不动,左指针向左移动取单词
var right = s.length - 1
var left = right
// 存放翻转后的字符
val sb = StringBuilder()
while (left >= 0) {
// 查找第一次出现的空格
while (left >= 0 && s[left] != ' ') left--
sb.append(s.substring(left + 1, right + 1) + " ")
while (left >= 0 && s[left] == ' ') left--
// 右指针移动
right = left
}
return sb.toString().trimEnd()
}
fun reversStringByQueue(s: String):String {
var left = 0
// 构建双端队列
val deque: Deque<String> = ArrayDeque()
val sb = StringBuilder()
while (left <= s.length - 1) {if (s.isNotEmpty() && s[left] == ' ') {
// 将单词 push 到队列头部
deque.offerFirst(sb.toString())
//
sb.setLength(0)
} else if (s[left] != ' ') {sb.append(s[left])
}
// 移动指针
++left
}
// 插入最后一个单词
deque.offerFirst(sb.toString())
return (deque.toTypedArray() as Array<String> ).joinToString(separator = " ")
}