Check if given string is a palindrome using stack [closed]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 02:01:41
import java.util.Stack;

public class PalindromeTest {

    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.");

    }
}

The general idea of doing this with a stack is extremely simple. I don't have time to syntax and Java code, but this is the concept in pseudocode.

string s = "test"
for i=0 to s.length
stack->push(s[i])

This would push t->e->s->t from left to right. So the resulting stack would look like this:

TOP -> |t|s|e|t| <- BOTTOM

Now, since the LAST character of the string is on top, you just need to pop until the stack is empty and store it in a string. This will be the reverse of the original string. You can then compare this string with the original, and if it matches you have a palindrome.

In this case you would do:

while(pop != '')
string s += pop'd character

So you would grab t, then s, then e and finally the first t and have s = tset. Comparing this to "test", it is not a palindrome.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!