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

题目描述:

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

示例 1:

  输入:

    Let's take LeetCode contest

  输出:

    s'teL ekat edoCteeL tsetnoc

 

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

 

算法:

根据题意,需要保持字符串中每个单词的顺序的情况下,反转每个单词,并且保存空格。

可以对整个字符串进行遍历,当遇到空格时,处理之前保存下来的单词,反转处理后再加入到要返回的字符串中。

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     string reverseWords(string s) {
 9         string backstr = "";
10         string words = "";
11         for(int i = 0; i < s.length(); i++)
12         {
13             
14             if(s[i] == ' ')
15             {
16                 reverse(words.begin(), words.end());
17                 backstr += words;
18                 backstr += " ";
19                 words = "";
20                 continue;
21             }
22             words += s[i];
23         }
24 
25         //针对最后一个单词再进行反转操作
26         reverse(words.begin(), words.end());
27         backstr += words;
28         
29         return backstr;
30     }
31 };
32 
33 int main()
34 {
35     string str = "Let's take LeetCode contest";
36     Solution s;
37     cout << "反转的字符串为:" << s.reverseWords(str) << endl;
38     return 0;
39 }

 

posted @ 2019-01-05 10:04  小王点点  阅读(94)  评论(0)    收藏  举报