Reputation: 7356
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");
}
}
}
Upvotes: 1
Views: 1167
Reputation: 10238
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.
Upvotes: 1
Reputation: 1575
Use the below version of isPalindrome
method, Stack
object was getting instantiated in each iteration of loop and hence you were not getting the expected behavior.
public boolean isPalindrome(String s) {
stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
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);
}
Upvotes: 0
Reputation: 15698
You should initialise the stack outside the loop i.e.
for (int i = 0; i < s.length(); i++) {
stack = new Stack<Character>();
stack.push(s.charAt(i));
top++;
}
should be
stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
top++;
}
Upvotes: 0