Pergunta de entrevista da empresa Google

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

Respostas da entrevista

Sigiloso

29 de jul. de 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

Sigiloso

11 de ago. de 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?