Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words is always separated by a single space.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Could do it in-place without allocating extra space?
1, the beginning of the idea is to find the first and last word, and then exchange them two, but the problem is that two words of inconsistent length will be very troublesome, you need to move the remaining strings throughout, cumbersome, and inefficient.
2, reference to discuss, found very simple idea, is divided into two steps: The first step is to put the whole string upside down, the second step is to turn back and then each word reversed once.
Public classSolution { Public voidReversewords (Char[] s) {intLen =s.length; Reverse (s),0, Len-1); intStart = 0; for(inti = 0; i < len-1; i++){ if(S[i] = = ") {Reverse (S, start, I-1); Start= i + 1; }} reverse (S, start, Len-1); } Private voidReverseChar[] s,intStartintend) { while(Start <end) { CharCH =S[start]; S[start]=S[end]; S[end]=ch; Start++; End--; } }}
Leetcode 186. Reverse Words in a String II rotating character array----------java