Sword Finger offer 44: Reversal Word Sequence

Keywords: C++

1 Topic Description

Niu Ke recently came to a new employee, Fish. Every morning he always took an English magazine and wrote some sentences in his notebook. Colleague Cat was interested in what Fish had written. One day he borrowed it from Fish and couldn't read it. For example, "student. a am I". Later, I realized that this guy had reversed the order of sentences and words. The correct sentence should be "I am a student." Cat is not good at flipping these words one by one. Can you help him?

2 Thoughts and Methods

First flip the string as a whole and then flip each word again. Overall flip of strings:.tneduts a ma i,

3 C++ Core Code

 1 class Solution {
 2 public:
 3     string ReverseSentence(string str) {
 4      int len = str.size();
 5      int start = 0;
 6      for(int i = 0; i < len; i ++)
 7      {
 8          if(str[i] == ' ')
 9          {
10              reverse(str.begin()+start, str.begin()+i);
11              start = i+1;
12          }
13          if(i == len-1)
14          {
15              reverse(str.begin()+start, str.end());
16          }
17      }
18      reverse(str.begin(), str.end());
19      return str;
20     }
21 };
 1 class Solution {
 2 public:
 3     string ReverseSentence(string str) {
 4         int len = str.length();
 5         string &temp = str;
 6         reserve(temp,0,len-1);
 7         int s = -1;
 8         for(int i=0;i<len;i++){
 9             if(str[i] == ' '){
10                 reserve(temp,s+1,i-1);
11                 s = i;
12             }
13         }
14         reserve(temp,s+1,len-1);
15         return str;
16     }
17     void reserve(string &s,int start,int end){
18         char temp;
19         while(start < end){
20             temp = s[start];
21             s[start] = s[end];
22             s[end] = temp;
23             start++;
24             end--;
25         }
26     }
27 };

Reference material

https://blog.csdn.net/weixin_40271182/article/details/84281680

Posted by chancho on Wed, 02 Oct 2019 23:02:02 -0700