Yatra.com Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
Why a more complicated one is required ? if more than 1 white space is a valid condition between words . Then just eat up the first white space after every word & Push other white spaces in to the stack . while recreating the string , just follow the above rule , with only one modification that don't insert a white space after a white space is poped from the stack .
import java.io.*;
import java.util.*;
public class str1
{
public static void main(String a[])
{
String str="my name is sonam";
String[] s=new String[100];
int i;
StringTokenizer st=new StringTokenizer(str);
int n=st.countTokens();
//st.nextToken();
for(i=0;i<n;i++)
s[i]=st.nextToken();
for(i=n-1;i>=0;i--)
System.out.print(" "+s[i]);
}
}
Following solution uses a stack ( i.e, some extra space ) .
- saikat January 25, 20121. traverse the string , when ever a space is found we can assume we have reached the end of a word . Now , treat this word as a separate string and push it in a stack . Keep on doing so until the string is finished
2. Now pop the stack & put it back into the original string from the start . While doing so , remember to put a space after every single pop , except the last one .