思路
先反转整个字符串,再每个单词进行反转
public class Solution {public String reverseWords(String s) {if (s == null) return null;char[] a = s.toCharArray();int n = a.length;// 1.反转整个字符串reverse(a, 0, n - 1);// 2.反转每一个单词reverseWords(a, n);// 3.去掉空格return cleanSpaces(a, n);}void reverseWords(char[] a, int n) {int i = 0, j = 0;//i指向要反转的第一个元素 j指向最后一个元素while (i < n) {while (i < j || i < n && a[i] == ' ') i++; // skip spaceswhile (j < i || j < n && a[j] != ' ') j++; // skip non spacesreverse(a, i, j - 1); // reverse the word}}// 去掉开头的中间的多余空格String cleanSpaces(char[] a, int n) {int i = 0, j = 0;while (j < n) {while (j < n && a[j] == ' ') j++; // skip spaceswhile (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaceswhile (j < n && a[j] == ' ') j++; // skip spacesif (j < n) a[i++] = ' '; // keep only one space}return new String(a).substring(0, i);}// 反转从i到j的部分private void reverse(char[] a, int i, int j) {while (i < j) {char t = a[i];a[i++] = a[j];a[j--] = t;}}}
