Google Interview Question

How do you efficiently reverse the order of the words in a string?

Interview Answers

Anonymous

Jul 29, 2010

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; }

1

Anonymous

Aug 11, 2010

I would have to ask for the criteria of efficiency (number of operations? memory utilization?). I'd push the sentence into a stack word by word, then construct a new string by popping words from a stack....but is it efficient? depends on the criteria, right?