Jobdu recently arrived with a new employee, fish, who always takes an English magazine in the morning and writes some sentences in the book. Colleague Cat was interested in what Fish wrote, one day he borrowed it from fish, but couldn't read it. For example, "student. A am I ". Later realized that this guy turned the sentence in the order of words, the correct sentence should be "I am a student." Cat Flip One by one the order of these words is not good, can you help him?
Method 1: Normal method, encountered "to take out to assign value."
1 classSolution {2 Public:3 stringReversesentence (stringstr) {4 if(Str.size () <1)return "";5 string:: Iterator Left=str.end ()-1;6 string:: Iterator right=str.end ();7 strings;8 while(left!=Str.begin ()) {9 if(*left==' '){Ten for(string:: Iterator it=left+1; it<right;it++){ Ones+=*it; A } -s+=' '; -right=Left ; theleft--; - Continue; - } -left--; + } - for(string:: Iterator it=left;it<right;it++) +s+=*it; A returns; at } -};
Method Two: First partial rollover, and then unified Flip, the same title flipped the string.
I record character, J Record '
1 classSolution {2 Public:3 stringReversesentence (stringstr) {4 for(inti =0, j =0; I < Str.length () && J <str.length ();) {5 while(I < Str.length () && str[i] = =' ') ++i;6j =i;7 while(J < Str.length () && str[j]! =' ') ++J;8Reverse (str, I, J-1);9i =J;Ten } OneReverse (str,0, Str.length ()-1); A returnstr; - } - voidReversestring& STR,intBinte) { the if(b >= E)return; - while(b <e) { - CharTMP =Str[b]; -STR[B] =Str[e]; +Str[e] =tmp; -b++; +e--; A } at } -};
Flip word order Column