Tuesday, June 3, 2014

Problem #4

Problem: Given an input string, reverse the string word by word.

Example: s = "the cat was fat"
output: fat was cat the

Algorithm: This problem is simple enough. In order to do the problem, I used a stack. A stack is a data structure that uses the last in first one idea. I started by splicing the input string on all white space, though doing this on spaces would be fine as well. Then, I looped through the resulting array and pushed all items into a stack. After, in order to get the reverse sentence, I simply popped everything off the stack and printed each word.

Full Code:
import java.util.*;

public class ReverseString {
public static void main(String[] args) {
// get input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Enter your sentence: ");
String s = scan.nextLine();
String[] arr = s.split("\\s+");
Stack<String> list = new Stack<String>();
for (int i = 0; i < arr.length; i++){
if (!arr[1].equals("")){
list.push(arr[i]);
}
}
// print the string in reverse
for (int j = 0; j < arr.length; j ++){
System.out.print(list.pop() + " ");
  }
  }
}

No comments:

Post a Comment