Pregunta de entrevista de Microsoft

Write an algorithm to reverse a string. Apply that algorithm to reverse a sentence.

Respuesta de la entrevista

Anónimo

26 sept 2012

Reversing a string is easy: Index at the start moving toward the end, index at the end moving to the front. Swap the letters at each index and increment / decrement the indices respectively. O(n) My first attempt at reversing the sentence, I reversed the entire sentence string, then split the sentence into words and reversed each word. O(n * w). The best way is to split on white spaces first and make the previous algorithm generic so that you aren't just constrained to swapping letters. Then swap words of a sentence in the same way that you would swap letters of a word. O(w)