A palindrome is a string which, when reversed, is the same string.
The following code contains two implementations of checking if a string is a palindrome:
isPalindrome()
works by iteratively comparing the first character with the last character, the second character with the second last character, and so forth moving towards the middle of the string from both ends. If the characters match, the algorithm continues until the middle of the string. If the characters do not match, the string is determined to therefore not be a palindrome. If the middle of the string is reached, the string must be a palindrome.isPalindromeWithStack()
works by reversing the string using a stack and then checking if the original string is the same as the reversed string.
Palindrome.java
On implementing isPalindromeWithStack()
, refer to my stack implementation in java.
revereString()
uses a stack to reverse the string. However, reversing a string in place is much more effecient.
public class Palindrome { public static void main(String[] args) { System.out.println(isPalindromeWithStack("abccba")); } /** * Checks if the specified string is a palindrome. * * @param str * * @return True, if the string is a palindrome, false otherwise. */ public static boolean isPalindrome(String str) { // If the length of the string is 0 or 1, it must be a palindrome. if(str.length() == 0 || str.length() == 1){ return true; } // Start by checking the outer characters, moving inwards. if(str.charAt(0) == str.charAt(str.length() - 1)){ // Cut off the ends, and re-check. return isPalindrome(str.substring(1, str.length() - 1)); } // If we have gotten here, it means that it is not a palindrome. return false; } /** * Checks if the string is a palindrome, using MyStack. * * @param str * * @return */ public static boolean isPalindromeWithStack(String str) { // Reverse the string. String strReversed = reverseString(str); // If the strings are the same, we have a palindrome, by definition. return str.equals(strReversed); } /** * Takes a string and reverses it, using stacks. * * @param str * * @return */ public static String reverseString(String str) { // Define the reversed string. String strReversed = ""; // Create the stack. MyStack stack = new MyStack(); // Iterate through each character. for(int i=0; i < str.length(); i++){ // Add the character to the stack. stack.push(str.charAt(i)); } // Now go through the stack until it's empty, and concatenate each char. while(!stack.empty()){ // Create the reversed string character by character. strReversed += stack.pop(); } // Return the reversed string. return strReversed; } }
Hi, thanks for the great work here…I am new to java, can you tell me which out of the above two solutions is more efficient, and why?
Thanks,
Mansi