Reverse a given sentence in Java

前端 未结 14 1905
别跟我提以往
别跟我提以往 2020-11-27 04:52

Can anyone tell me how to write a Java program to reverse a given sentence?

For example, if the input is:

\"This is an interview question\"

14条回答
  •  萌比男神i
    2020-11-27 05:24

    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 stack = new Stack();
    
    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(" ");
        }
    }
    

提交回复
热议问题