|
| 1 | +package com.thealgorithms.stacks; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | + |
| 5 | +/** |
| 6 | + * A class that implements a palindrome checker using a stack. |
| 7 | + * The stack is used to store the characters of the string, |
| 8 | + * which we will pop one-by-one to create the string in reverse. |
| 9 | + * |
| 10 | + * Reference: https://www.geeksforgeeks.org/check-whether-the-given-string-is-palindrome-using-stack/ |
| 11 | + */ |
| 12 | +public final class PalindromeWithStack { |
| 13 | + private LinkedList<Character> stack; |
| 14 | + |
| 15 | + /** |
| 16 | + * Constructs an empty stack that stores characters. |
| 17 | + */ |
| 18 | + public PalindromeWithStack() { |
| 19 | + stack = new LinkedList<Character>(); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Check if the string is a palindrome or not. |
| 24 | + * Convert all characters to lowercase and push them into a stack. |
| 25 | + * At the same time, build a string |
| 26 | + * Next, pop from the stack and build the reverse string |
| 27 | + * Finally, compare these two strings |
| 28 | + * |
| 29 | + * @param string The string to check if it is palindrome or not. |
| 30 | + */ |
| 31 | + public final boolean checkPalindrome(final String string) { |
| 32 | + // Create a StringBuilder to build the string from left to right |
| 33 | + StringBuilder stringBuilder = new StringBuilder(string.length()); |
| 34 | + // Convert all characters to lowercase |
| 35 | + String lowercase = string.toLowerCase(); |
| 36 | + |
| 37 | + // Iterate through the string |
| 38 | + for(int i = 0; i < lowercase.length(); ++i) { |
| 39 | + char c = lowercase.charAt(i); |
| 40 | + if (c >= 'a' && c <= 'z') { |
| 41 | + // Build the string from L->R |
| 42 | + stringBuilder.append(c); |
| 43 | + // Push to the stack |
| 44 | + stack.push(c); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // The stack contains the reverse order of the string |
| 49 | + StringBuilder reverseString = new StringBuilder(stack.size()); |
| 50 | + // Until the stack is not empty |
| 51 | + while (!stack.isEmpty()){ |
| 52 | + // Build the string from R->L |
| 53 | + reverseString.append(stack.pop()); |
| 54 | + } |
| 55 | + |
| 56 | + // Finally, compare the L->R string with the R->L string |
| 57 | + return reverseString.toString().equals(stringBuilder.toString()); |
| 58 | + } |
| 59 | +} |
0 commit comments