A palindrome is any word, phrase, or sentence that reads the same forward and ba
ID: 3674965 • Letter: A
Question
A palindrome is any word, phrase, or sentence that reads the same forward and backward. For example:
Able was I ere I saw Elba
A man A plan a canal Panama
Desserts I stressed
Kayak
abcde edcba
Write a program that uses a stack to determine if a string of characters is a palindrome. This program will ask the user to enter a string, then printout a statement indicating whether or not the string was a palindrome. You may use any data structure you wish to create the stack so long as the stack is implemented and used correctly. Name your demo class (containing the main method) PalindromeDemo.
Explanation / Answer
import java.util.Scanner;
public class PalindromeDemo {
public static boolean isPalindrome(String str){
boolean isPal = true;
//creating stack
Stack stack = new Stack(str.length());
//push all character into stack
for(int i=0; i<str.length(); i++){
stack.push(str.charAt(i));
}
// now traverse str and check current character with top of stack
for(int i=0; i<str.length(); i++){
char c = (char) stack.pop();
// if not equal, break
if(Character.toLowerCase(c) != Character.toLowerCase(str.charAt(i))){
isPal = false;
break;
}
}
return isPal;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
System.out.println("Enter a string: ");
str = sc.nextLine();
System.out.println(isPalindrome(str));
}
}
/*
Output:
Enter a string:
Able was I ere I saw Elba
true
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.