The topics are as follows:
Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue ",
Return " blue is sky the ".
Click to show Clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.
- Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
- How about multiple spaces between and words?
Reduce them to a single space in the reversed string.
The title requires not only that the words in the string be rotated, but also that the test case contains a string with a space in the tail and the number of spaces between the words greater than 1. So to deal with the space, the string processing space is certainly less than or equal to the original string length, considering the way to reduce the space time by moving characters, my idea is to first calculate the extra space after the string should be the length, and then redefine a temporary string, open up the space of the final length should be. The original string is then copied in reverse order to the newly defined string variable, guaranteeing that the trailing extra space is removed, leaving only one space between the words. Then, once each word is reversed, it realizes the function required by the topic. The AC code is as follows:
Class Solution {Public:void reversewords (string &s) {if (S.empty ()) return;int count = 0;int index = 0, indextemp = 0, begin = 0, end = S.length () -1;while (s[begin] = = "&& begin<s.length ()-1) begin++;while (s[end] = =" && Amp end>0) end--;if (end = = 0 && S[end] = = ") {s =" "; return;} else if (end = = 0) {s = s.substr (0,1); return;} index = begin;while (index <= end) {if (s[index] = = ") {count++;while (s[index] = = ') index++;} count++;index++;} String Temp (count, ' n '); index = End;indextemp = 0;while (index >= begin) {if (s[index] = = ") {Temp[indextemp] = S[index]; while (s[index] = = ") index--;indextemp++;} Temp[indextemp] = s[index];indextemp++;index--;} Indextemp = 0;begin = -1;end = -1;while (Indextemp < count) {if (temp[indextemp]! = "&& begin = =-1) {begin = 0; }else if (indexTemp-1 >= 0 && temp[indextemp-1] = = "&&temp[indextemp]! =") {begin = Indextemp;} else if ((Indextemp+1 < count && temp[indextemp+1] = = "&&Amp TEMP[INDEXTEMP]! = ") | | ((indextemp = = count-1) &&temp[indextemp]! = ")) {end = Indextemp;reverse (temp, begin, end);} indextemp++;} s = temp; }void reverse (string &s, int begin, int end) {while (Begin < end) {Char temp = s[begin];s[begin] = s[end];s[end] = tem p;begin++;end--;}};