Microsoft interview question

Write a function that takes an input string, consisting of several words separated by spaces, and print out each word reversed, keeping the same order within the string.

Interview Answers

Anonymous

15 Oct 2010

Create a stack. Traverse the string and push the characters onto the stack until a space is encountered, then print all the characters off the stack until it's empty. When the end of the list is reached, empty and print the stack.

1

Anonymous

10 Jan 2011

I know that a Java answer isn't always what MS likes to hear. However, the technique is essentially the same if it's C#, C++, or even C. Extracting the tokens from the string and reversing them in the same order as the original string is the trick. ---------------------------------------------- import java.util.StringTokenizer; public class MsTest { public static void main(String[] args) { // TODO Auto-generated method stub String aString = "ABC 123 Doe Ray Me Fala=la 890"; System.out.println( "Original String: " + aString ); StringReverseElements( aString ); } private static void StringReverseElements(String Mess ) { StringTokenizer st = new StringTokenizer (Mess, " "); String tmpString; System.out.print( "Reversed String: " ); while (st.hasMoreTokens ()) { tmpString = (st.nextToken()); PrintReverse( tmpString.toCharArray(), tmpString.length()); } } private static void PrintReverse( char[] AnArray, int iLen ) { for ( int kk = 0; kk < iLen; kk++ ) System.out.print( AnArray [ iLen - kk -1] ); System.out.print( ' ' ); } }

Anonymous

10 Jan 2011

Clay - That would absolutely work, but during my interview I was told I couldn't use library functions, including Tokenizer.

Anonymous

10 Jan 2011

I see. Not having access to library functions makes it a bit more challenging.