557. 反转字符串中的单词 III

ⅰ亾dé卋堺 提交于 2019-12-18 05:59:05

链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/

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

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

思路:先用一个临时的字符串变量存储,遇到空格或者末尾时,用reverse()函数翻转该字符串变量,再将其加入总的字符串中,注意空格和结束符也要加入到字符串中。

class Solution {
public:
    string reverseWords(string s) {
        string a = "";
        string temp = "";
        int len = s.length();
        for(int i = 0; i <= len; i++)
        {
            if(s[i] == ' ' || s[i] == '\0')
            {
                reverse(temp.begin(), temp.end());
                a = a + temp;
                a = a + s[i];
                temp = "";
            }
            else
                temp += s[i];
        }
        return a;
    }
};

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!