Recommended reading Left-handed string The principles are based on:
I. solution I
class Solution { public: string ReverseSentence(string str) { int len = str.size(); if (len == 0) return ""; string res = str; for(int i = len - 1; i >= 0; --i){ if(str[i] == ' ') res[len - 1 - i] = str[i]; else{ int begin = i, end = i; while (begin >= 1 && str[begin - 1] != ' ') begin--; for(int k = begin; k <= end; ++k,--i) res[len - 1 - i] = str[k]; i += 1; } } return res; } };
II. Solution II
class Solution { public: string ReverseSentence(string str) { int len = str.size(); if (len == 0) return ""; for(int i = 0; i < len; ++i) if(str[i] != ' '){ int begin = i,end = i; while(end < len && str[end] != ' ')end++; end == len - 1?i = end: i = --end; myReverse(str, begin, end); } myReverse(str, 0, len - 1); return str; } void myReverse(string &str, int begin, int end){ //Internal exchange function int len = str.size(); //String length if(begin < 0 || end >= len) //begin and end are just Subscripts return; while(begin < end){ char temp = str[begin]; str[begin] = str[end]; str[end] = temp; begin++;end--; } } };
3, Solution 3
Traverse from the front to the back. When you encounter a space, press the previously read one to the front of the result and add a space. Finally, the loop ends; if the string used to read the string is not empty, press it to the front of the result again, of course, this time there is no need to add a space at the front of the result.
class Solution { public: string ReverseSentence(string str) { string res = "", tmp = ""; for(int i = 0; i < str.size(); ++i){ if(str[i] == ' ') { res = " " + tmp + res;//After a space is encountered, press the previously read result to the front and add a space tmp = ""; } else tmp += str[i]; } if(tmp.size()) res = tmp + res; return res; } };