Reversing English sentences means reversing the order of the words in the sentence, as shown in the following example:
Input: Wo shi Zhong guo ren
Output: ren guo zhong shi wo
The intuitive solution is to first extract each word, and then calculate the position of each word reversal, and finally fill in the corresponding position of the word. This scheme occupies not only the auxiliary space, but also the computational complexity. Another option is to see the whole sentence as a string, reverse the order of the string letters (including spaces), and then reverse the alphabetical order of each word. The reversal of the word letter means:
Input: Wo shi Zhong guo ren
Output: Ner oug gnohz IHS ow
Here is the code for the second way of thinking:
#include "stdafx.h"#include <string.h>#include <iostream>#include <vector>using namespace STD;voidReverseString (CharStr[],intStartintEnd) { for(inti = Start,j = end; I < J; ++i,--j) {Charc = Str[i]; Str[i] = Str[j]; STR[J] = c; }}voidReverseString (CharStr[]) {intLength =strlen(str); ReverseString (str,0, Length-1);}voidReversesentence (CharStr[]) {reversestring (str); vector<int>Splitindex;intLength =strlen(str);//Record the position of the word separator (space), place a dummy space at the beginning of the sentenceSplitindex.push_back (-1); for(inti =0; i < length; ++i) {if(Str[i] = ="') Splitindex.push_back (i); }//end of sentence place a dummy spaceSplitindex.push_back (length);intCount = Splitindex.size ()-1; for(inti =0; I < count; ++i) {reversestring (Str,splitindex[i] +1, splitindex[i+1] -1); }}int_tmain (intARGC, _tchar* argv[]) {CharStr[] ="wo shi Zhong guo ren";cout<<str<<endl; Reversesentence (str);cout<<str<<endl;return 0;}
Program run:
The program only considers the English alphabet input, and does not consider punctuation, all words separated by a space.
One question per day: reverse English sentences