views:

619

answers:

8

This was the question asked me in amazon interview. , Write a program to reverse a given sentence like "This is interview question" the output must be "question interview is this".Can any tell me how to get this done?

Thanks in advance

+11  A: 

You split the string by the space then iterate over it backwards to assemble the reversed sentence.

string[] words =  "This is interview question".split(" ");

string rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
   rev += words[i] + " ";
}

// rev = "question interview is This "

// can also use StringBuilder:
StringBuilder revb = new StringBuilder;
for(int i = words.length - 1; i >= 0 ; i--)
{
   revb.Append(words[i]);
   revb.Append(" ");
}
// revb.toString() = "question interview is This "
Oded
Won't this add a trailing space?
Skilldrick
Is there a reason you're concatenating to a `string` (which creates a new `string` object every time) instead of using a `StringBuilder`?
Christopher Parker
@Christopher Parker - Simply showing the principle. This can of course be adapted to be more performant (if needed).
Oded
@Skilldrick - `Rev.trim();` to remove the trailing space. Not that the question specified, but like you, I dislike extra spaces like that.
Onion-Knight
I wouldn't use trim() - It creates an entirely new String. Better to perform a second check of i within the loop IMHO.
Adamski
@Adamski what is that saying about optimisation...
Gareth Davis
+4  A: 

Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.

String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
    output += array[i];
    if (i != 0) { output += " "; }
}
Rich Adams
+10  A: 
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = ArrayUtils.join(reversedWords, " ");

(using ArrayUtils from commons-lang, but these are easy methods to write - just a few loops)

Bozho
Using an outside library for an interview question this simple isn't going go over that well.
D'Nabre
well. that over go to going isn't simple this question interview an for library outside an Using
R. Bemrose
@D'Nabre - if you know commons-lang well enough to write that code, I think it would go VERY well over that well.
Thorbjørn Ravn Andersen
@D'Nabre I don't think so. If they ask you to explain how are these utility methods implemented, you'd always be able to explain, but thus you are increasing the elegance of your code. What if these methdos were present in `java.util.Arrays`?
Bozho
If someone demonstrated appreciation of the *know and use the libraries* guideline in an interview, I'd definitely consider that a plus.
Jonik
+1  A: 

Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:

To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.

(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).

Lord Torgamus
+3  A: 

a every boring bit of java:

List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
    b.append(s).append(' ');
}
b.toString().trim();

in groovy it's a little bit more readable:

"this is an interview question"
    .split("\\s")
    .reverse()
    .join(' ')
Gareth Davis
@Oded's is a lot nicer...way to used to just using collections.
Gareth Davis
+5  A: 

Just being different: a recursive solution. Doesn't add any extra spaces.

public static String reverse(String s) {
   int k = s.indexOf(" ");
   return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}


System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"

I will also improve on the split solution by using \b instead (it's so obvious!).

    String[] parts = "Word boundary is better than space".split("\\b");
    StringBuilder sb = new StringBuilder();
    for (int i = parts.length; i --> 0 ;) {
        sb.append(parts[i]);
    }
    System.out.println("[" + sb.toString() + "]");
    // prints "[space than better is boundary Word]"
polygenelubricants
+1  A: 

I also give it a try: Here's a version using a stack and a scanner:

String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();

while(sc.hasNext()) {
    stack.push(sc.next());
}

StringBuilder output = new StringBuilder();

for(;;) { // forever
    output.append(stack.pop());

    if(stack.isEmpty()) {
        break; // end loop
    } else {
        output.append(" ");
    }
}
Searles
+1  A: 

public class ReverseString {

    public void reverse(String[] source) {

        String dest = "";
        for (int n = source.length - 1; n >= 0; n--) {
            dest += source[n] + " ";
        }
        System.out.println(dest);

    }

    public static void main(String args[]) {
        ReverseString rs = new ReverseString();
        String[] str = "What is going on".split(" ");
        rs.reverse(str);

    }

}
harigm