Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Update (2015-02-12):
For C programmers:try to solve it in-place in O(1) space.
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.
Hide TagsStringAnalysis: If you encounter multiple spaces between words, can only return one, and can not have words, and the C language programmer requires a space complexity of O (1), so we can only modify the original string s between, and cannot declare a new string. The first step: anyway the whole string Part two: Anyway, a single word in the third part: put the flipped word in the right place, where the right place is the front without space.
The Writepos marks the appropriate location, which is where it will be written.
Fourth: Changing the size of a string
In addition, we finally press into a space, is for the final word can be unified processing.
Note that this code is meant to handle the case where the entire string is space.
if 0 // Remove the latest space 1 ); Else s.resize (0); // The str only contains space
In short, this problem is a good body, the problem of small universe, a lot of details need to deal with.
AC Code:
classSolution {Private: voidReverseword (string&s,intLeftintRight ) { Chartmp; while(Left <Right ) {tmp=S[left]; S[left]=S[right]; S[right]=tmp; Left++; Right--; } } Public: voidReversewords (string&s) {if(s.size () = =0) return; //reverse All wordsReverseword (s),0, S.size ()-1); S.push_back (' ');//inorder to handler the latest part intSize =s.size (); intWritepos =0;//position which 'll be written intleft =0, right =0; for(inti =0; i < size; i++) { //convert multiple spaces to one space if(S[i]! =' ') { if(i = =0|| s[i-1] ==' ') { left=i; Right=i; } Else Right++; } Else //if (s[i] = = ") { if(I >0&& s[i-1] !=' ') { //cout << "left\t" << left << Endl; //cout << "right\t" << right<< Endl;Reverseword (S, left, right); //move the part to Writepos//it means Memmove while(Left <=Right ) {S[writepos+ +] = s[left++]; } S[writepos++] =' ';//add space after the word } } } if(Writepos >0)//Remove the latest spaceS.resize (Writepos-1); ElseS.resize (0);//The str only contains space }};
[Leetcode] Reverse Words in a String