I wrote a palindrome using stacks in java. But, due to some reason while popping the stack the program is not working as expected. I have also tried using the top and iterate using this variable. Either ways it is not working.
import java.util.Stack;
class Palindromer {
Stack<Character> stack = null;
int top = -1;
public boolean isPalindrome(String s) {
for (int i = 0; i < s.length(); i++) {
stack = new Stack<Character>();
stack.push(s.charAt(i));
top++;
}
System.out.println("value of top is " + top);
String returnString = "";
while (!stack.isEmpty()) {
returnString += stack.pop();
}
System.out.println(returnString);
return returnString.equals(s);
}
}
public class PalindromeChecker {
public static void main(String[] args) {
Palindromer palin = new Palindromer();
if (palin.isPalindrome("BananaB")) {
System.out.println("is palindrome");
} else {
System.out.println("not a palindrome");
}
}
}
You should place the new Stack<Character>();
outside the loop.
The way you do it:
for (int i = 0; i < s.length(); i++) {
stack = new Stack<Character>();
stack.push(s.charAt(i));
top++;
}
the stack
variable is reassigned each loop and does contain only one character after the loop. Change it into
stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
top++;
}
BTW: Better declare stack
and top
in the isPalindrome
method. So you get rid of the error in top
with further calls.