1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public void reverseWords(char[] s) { reverse(s, 0, s.length - 1);
int j = 0; while (j < s.length) { int i = j; while (j < s.length && s[j] != ' ') { j++; }
reverse(s, i, j - 1); j++; } }
private void reverse(char[] chars, int i, int j) { while (i < j) { swap(chars, i++, j--); } }
private void swap(char[] chars, int i, int j) { char tmp = chars[i]; chars[i] = chars[j]; chars[j] = tmp; } }
|
References
186. Reverse Words in a String II