Data Structures in Java. Assignment 4: A palindrome is any word, phrase, or sent
ID: 3886422 • Letter: D
Question
Data Structures in Java.
Assignment 4:
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. Do not use the Stack class in the Java API.
Explanation / Answer
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Remove whitespaces from string
input = String.join("", input.split("\s"));
char[] letters = input.toCharArray();
Stack<Character> st = new Stack<Character>();
for (int i = 0; i < letters.length/2; i++)
st.add(letters[i]);
int mid;
if (letters.length % 2 == 0)
mid = letters.length/2;
else
mid = 1 + letters.length/2;
boolean isPal = true;
for (int i = mid; i < letters.length; i++) {
char cur = st.pop();
if (cur == letters[i])
continue;
isPal = false;
break;
}
if (isPal)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
You can run and test it at :
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.