leetcode【151】-Reverse Words in a String

题目要求:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

思路:

一个字符一个字符的遍历:

  遇到非空字符->①继续向后遍历

  遇到空字符->①单词入栈;②继续向后遍历

需要的变量:

  flag:ture状态下遇到空格可将单词入栈;false状态下遇到空格,说明前面是连续的空格,需继续向后遍历;

  beginpos:单词起始位置;

  word:栈,用于存放单词;

 1 #include<string>
 2 #include<stack>
 3 using namespace std;
 4 
 5 
 6 class Solution {
 7 public:
 8     void reverseWords(string &s) {
 9         stack<string> word;
10         int i = 0;
11         bool flag = false;
12         int beginpos = 0;
13         while (i <= s.size()){
14             if (0 == i){
15                 if (s[i] != ' '){
16                     beginpos = 0;
17                     flag = true;
18                 }
19             }
20             else if (i < s.size()){
21                 if (s[i] == ' '){
22                     if (flag){
23                         if (word.empty()){
24                             word.push(s.substr(beginpos, i - beginpos));
25                         }
26                         else{
27                             word.push(" ");
28                             word.push(s.substr(beginpos, i - beginpos));
29                         }
30                         flag = false;
31                     }
32                 }
33                 else{
34                     if (flag == false){
35                         beginpos = i;
36                         flag = true;
37                     }
38                 }
39             }
40             else if (i == s.size()){
41                 if (flag){
42                     if (word.empty()){
43                         word.push(s.substr(beginpos, i - beginpos));
44                     }
45                     else{
46                         word.push(" ");
47                         word.push(s.substr(beginpos, i - beginpos));
48                     }
49                 }
50             }
51             ++i;
52         }
53         s.clear();
54         while (!word.empty()){
55             s+=word.top();
56             word.pop();
57         }
58     }
59 };
原文地址:https://www.cnblogs.com/wangshujing/p/6838231.html