题解 | #翻转单词序列#

翻转单词序列

http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3

难度较低的题目。
在经历了前面的字符串处理地狱之后,这种题目我看过之后心里毫无波澜,甚至还有点想笑w。
言归正传,总体的思路是:将string作为char[]遍历,遇到空格则切词,并将切下的词入栈。最后按出栈顺序将字符串拼好即可。

需要注意空格的处理方式,这里我的做法是每次切词都加上空格,对头尾特殊处理。

class Solution {
public:
    string ReverseSentence(string str) {
        stack<string> stk;
        string temp = "";
        string result = "";
        for(int i = 0;i < str.length();i++){
            if(str[i] == ' '){
                if(!stk.empty()){
                    temp += str[i];
                }
                stk.push(temp);
                temp = "";
                continue;
            }
            temp += str[i];
            if(i == str.length() - 1 && !stk.empty()){
                temp += ' ';
                stk.push(temp);
            }
            else if(i == str.length() - 1){
                stk.push(temp);
            }
        }
        while(!stk.empty()){
            result += stk.top();
            stk.pop();
        }
        return result;
    }
};
全部评论

相关推荐

06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务