在js中使用栈反转句子

问题描述 投票:0回答:1

我想在 JavaScript 中使用 Stack 反转一个句子,所以在这里如果我输入,嘿,你好吗?并想完成输出?你嘿,所以我遍历循环并检查直到找到空间,然后压入该单词,然后从堆栈中弹出所有单词,但它没有显示未定义的内容,所以您如何纠正该代码?

function reverseSentence(S){
    let stack = [];
    let word="";
    for(let i=0;i<S.length;i++){
        while(S[i]!=' '&&i<S.length){ 
            word+=S[i]
            i++
        }
       return stack.push(word)
    }
    while(!stack.length){
       return stack.pop()
    }
}
console.log(reverseSentence("Hey, how are you doing?"))
javascript data-structures stack reverse
1个回答
0
投票

实现您所追求的目标的最简单方法可能是

function reverseSentence(S){
    return S.split(" ").reverse().join(" ");
}
console.log(reverseSentence("Hey, how are you doing?"));

不过,既然你用了“栈”这个词,下面就展示如何利用数组的push/pop来达到同样的目的

function reverseSentence(S){
    const stack = [];
    for(let i=0;i<S.length;i++){
        let word="";
        while(S[i]!=' '&&i<S.length){ 
            word+=S[i]
            i++
        }
       stack.push(word)
    }
    let reverse = stack.pop();
    while(stack.length){
       reverse += " " + stack.pop();
    }
    return reverse;
}
console.log(reverseSentence("Hey, how are you doing?"))

© www.soinside.com 2019 - 2024. All rights reserved.