Java Data Type How to - Check if given string is a palindrome using stack








Question

We would like to know how to check if given string is a palindrome using stack.

Answer

import java.util.Stack;
//from   w  w  w.  ja v  a 2 s  .c om
public class Main {
  public static void main(String[] args) {
    String input = "test";
    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < input.length(); i++) {
      stack.push(input.charAt(i));
    }
    String reverseInput = "";
    while (!stack.isEmpty()) {
      reverseInput += stack.pop();
    }
    if (input.equals(reverseInput)){
      System.out.println("Yo! that is a palindrome.");
    }else{
      System.out.println("No! that isn't a palindrome.");
    }
  }
}