leetcode 557翻转字符串

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

代码

class Solution {
public:
    string reverseWords(string s) {
        string result = "";
        stack<char> word;
        int flag = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] != ' ') 
                word.push(s[i]);
            if (s[i] == ' ' || i == s.length() - 1) {
                if (flag == 1) result += " ";
                while (!word.empty()) {
                    result += word.top();
                    word.pop();
                    flag = 1;
                }
            }
        }
        return result;
    }
};

思路

从头开始遍历字符串,不是空格的时候入栈,遇到空格的时候开始将栈中元素依次出栈,即可完成逆序输出。同时要注意空格的输出,设置变量flag,一个单词输出结束后输出空格。最末尾的单词也要注意。

参考 https://blog.csdn.net/liuchuo/article/details/711567

今天这道题用c语言做了半天都做不出来,越来越觉得C语言麻烦了。上网搜了大神的代码。

猜你喜欢

转载自blog.csdn.net/qq_38290604/article/details/88123147