How do you efficiently reverse the order of the words in a string?
Sigiloso
Just need to polish the boundary cases, but the main algorithm is basically this. Runs in O(n), where n is the number of characters in the string. reverseWords(String phrase) { char[] array = phrase.toCharArray(); reverse(array, 0, array.length); int i = 0, j = 0; while (i < array.length) { while (i < array.length && Char.isWhiteSpace(array[i])) i++; j=i; while (j < array.length && !Char.isWhiteSpace(array[j])) j++; reverse(array,i,j-1); } } reverse(char[] array, int j, int k) { for (int i = 0 ; i < (k-j)/2 ; i++) swap(array, j+i, k-i); } swap(char[] array, int j, int k) { char swap = array[j]; array[j] = array[k]; array[k] = swap; }