给定一个字符串,逐个翻转字符串中的每个单词。 **示例 1:** ``` 输入: "the sky is blue" 输出: "blue is sky the" ``` **示例 2:** ``` 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 ``` **示例 3:** ``` 输入: "a good example" 输出: "example good a" 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 ``` **说明:** - 无空格字符构成一个单词。 - 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 - 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 附赠姚老板的 :[JavaScript正则表达式迷你书(1.1版).pdf](https://github.com/sisterAn/JavaScript-Algorithms/files/4490629/JavaScript.1.1.pdf) [leetcode](https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/tu-jie-leetcodefan-zhuan-zi-fu-chuan-li-de-dan-ci-/)
Activity
hh-cheng commentedon Apr 16, 2020
kimixue commentedon Apr 16, 2020
方法一
方法二
sisterAn commentedon Apr 16, 2020
解法一:正则 + JS API
解法二:双端队列(不使用 API)
双端队列,故名思义就是两端都可以进队的队列
解题思路:
画图理解:
代码实现:
leetcode
[-]字节&leetcode151:翻转字符串里的单词[/-][+]图解字节&leetcode151:翻转字符串里的单词[/+]sisterAn commentedon Apr 16, 2020
@WeCheung:
你这种写法有问题,一是匹配的字符有限(
[\w!,]),二是需要考虑一下""或" "的情况,这种情况下str.match(/[\w!,]+/g)会返回null,就没办法继续执行下去了Bulandent commentedon Apr 17, 2020
zegezs commentedon Apr 20, 2020
function reverseString(params) {
const stringList = params.split(' ').filter((one) => one);
return stringList.reverse().join(' ')
}
MoruoFrog commentedon Apr 21, 2020
希望增加inplace的做法
msisliao commentedon Apr 26, 2020
zero9527 commentedon Apr 29, 2020
ron0115 commentedon May 25, 2020
官方题解,他不香吗?
Verahuan commentedon Jul 26, 2020
如果在第一种方法执行前进行一个判断会更加高效
var reverseWords = function(s) {
if( s==0) return ""
return s.trim().replace(/\s+/g, ' ').split(' ').reverse().join(' ')
};
CarberryChai commentedon Aug 7, 2020
syc666 commentedon Aug 19, 2020
str.replace(/ +/g,' ').trim().split(' ').reverse().join(' ')
qianlongo commentedon Aug 22, 2020
zhansingsong commentedon Sep 18, 2020
Keekuun commentedon Sep 26, 2020
var reverseWords = str => str.trim().split(' ').reverse().join(' ')Keekuun commentedon Sep 26, 2020
webpig commentedon Oct 20, 2020
AnranS commentedon Nov 17, 2020
RyanMeg123 commentedon May 25, 2022