Reverse Words in a String II

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 are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

先把每个词反转一遍, 再把整个string 反转一遍。

 1 public class Solution {
 2     public void reverseWords(char[] s) {
 3         for(int i = 0, j = 0; j <= s.length && i < s.length; j ++){
 4             if(j == s.length || s[j] == ' '){
 5                 reverse(s, i, j - 1);
 6                 i = j + 1;
 7             }
 8         }
 9         reverse(s, 0, s.length - 1);
10     }
11     
12     private void reverse(char[] c, int s, int e){
13         while(s < e){
14             char tmp = c[s];
15             c[s] = c[e];
16             c[e] = tmp;
17             s ++; e --;
18         }
19     }
20 }
原文地址:https://www.cnblogs.com/reynold-lei/p/4277374.html