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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
public class ReverseWordsInAStringII { public void reverseWords(char[] s) { if (s == null || s.length == 0) { return; } arrayReverse(s, 0, s.length - 1); for (int i = 0; i < s.length - 1; ) { int j = i + 1; while (j < s.length && s[j] != ' ') { j++; } arrayReverse(s, i, j - 1); i = j + 1; } } private void arrayReverse(char[] s, int start, int end) { if (s == null || s.length == 0 || start >= end) { return; } char tmp; for (int i = start; i <= (end + start) / 2; i++) { tmp = s[i]; s[i] = s[end + start - i]; s[end + start - i] = tmp; } } @Test public void test() { char[] s = new char[]{'a', 'f', ' ', 'g'}; reverseWords(s); } }
|