A palindrome is a word that reads the same way forward and backward, such as \"d
ID: 3798431 • Letter: A
Question
A palindrome is a word that reads the same way forward and backward, such as "dad" or "deed". You can determine if a word is a palindrome using a stack as follows: 1. Determine the length, n, of the word w. 2. Push the first n/2 characters of w, one at a time, onto a stack s. Each character pushed onto s is removed from w. 3. If n is odd, remove the first character of w. 4. If s is empty, then stop and declare w to be a palindrome. 5. Now, compare the top character in s with the the first letter of what remains in w. If the letters are the same pop the top letter from s, remove the cooresponding letter from w and go back to step 4. If the letters are not the same, then stop and declare w to be a non-palindrome. Write a function called isPalindrome which uses a stack of characters to implement the above algorithm. Note, isPalindrome takes a single string paramenter w and returns true if w is a palindrome and returns false otherwise.
Explanation / Answer
import java.util.Scanner;
import java.util.Stack;
public class Palindrome {
/**
* creating instance of Stack
*/
Stack<Character> s = new Stack<Character>();
/**
* isPalindrome method is checking for word is palindrome or not
*
* @param str
*/
public void isPalindrome(String str) {
/* creating instance of StringBuilder */
StringBuilder word = new StringBuilder(str);
/**
* calculating length
*/
int len = str.length();
for (int i = 0; i < len / 2; i++) {
/**
* inserting into stack
*/
s.push(str.charAt(i));
/**
* deleting character from word
*/
word.deleteCharAt(i);
}
if (len % 2 == 0) {
int index = 0;
/**
* checking character from word and popped from stack is same or not
* if it is not same then print not palindrome and return
*/
while (!s.isEmpty()) {
if (!s.pop().equals(word.charAt(index))) {
System.out.println(str + " not a palindrome");
return;
}
index++;
}
System.out.println(str + " is a palindrome");
} else {
word.deleteCharAt(0);
int index = 0;
while (!s.isEmpty()) {
if (!s.pop().equals(word.charAt(index))) {
System.out.println(str + " not a palindrome");
return;
}
index++;
}
System.out.println(str + " is a palindrome");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/**
* Prompt for user input
*/
System.out.println("Please Enter the word");
String str = input.nextLine();
Palindrome p = new Palindrome();
/**
* calling palindrome method
*/
p.isPalindrome(str);
}
}
/****************************output************************/
Please Enter the word
ded
ded is a palindrome
Please Enter the word
deed
deed is a palindrome
Thanks a lot
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.