题目
- 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。
- leetcode链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
思路
- 每个单词反转,再整个句子反转
- 注意前面后面和中间的空格
代码
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function (s) {
const words = s.split(/\s/).filter(word => word)
const reversedWords = words.map(word => reverse(word))
return reverse(reversedWords.join(' '))
}
function reverse(str) {
const arr = str.split('')
let left = 0
let right = arr.length - 1
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]]
left++
right--
}
return arr.join('')
}