题解 | #翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
```function ReverseSentence(str)
{
// write code here
if(str === ''){return ''} //特殊输入
let stack = []
let res1 = []
let res2 = []
let arr = [...str]
for(let i=0;i<arr.length;i++){
if(arr[i]===' '){
let temp =stack.join('')
res1.push(temp)
stack = []
continue
}
stack.push(arr[i])
if(i===arr.length-1){
let temp =stack.join('')
res1.push(temp)
stack = []
}
}
while(res1.length){
if(res1.length===1){
res2.push(res1.pop())
}
else {
res2.push(res1.pop().concat(' '))
}
}
return res2.join('')
}
//想用一下栈的方法,写出来这么复杂。。。建议还是直接 return str.split(' ').reverse().join(' ')
module.exports = {
ReverseSentence : ReverseSentence
};