Main.java 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import java.util.Stack;
  2. public class Main {
  3. public static void main(String[] args) {
  4. System.out.print("Enter a string: ");
  5. java.util.Scanner scanner = new java.util.Scanner(System.in);
  6. String input = scanner.nextLine();
  7. Boolean isPalindrome = palindrome(input);
  8. String not = "";
  9. if (!isPalindrome) {
  10. not = "not ";
  11. }
  12. System.out.println(input + " is " + not + "a palindrome");
  13. scanner.close();
  14. }
  15. // Returns true if the given string is a palindrome.
  16. // Method ignores spaces and capitalization.
  17. public static boolean palindrome(String s) {
  18. s = s.toLowerCase().replaceAll(" ", "");
  19. Stack<Character> stack = new Stack<>();
  20. char[] letters = s.toCharArray();
  21. for (int i = 0; i < s.length() / 2; i++) {
  22. stack.push(letters[i]);
  23. }
  24. int plus = 0;
  25. if (s.length() % 2 != 0) {
  26. plus = 1;
  27. }
  28. for (int i = (s.length() / 2) + plus; i < s.length(); i++) {
  29. if (stack.empty()) {
  30. return true;
  31. }
  32. if (letters[i] == stack.peek()) {
  33. stack.pop();
  34. } else {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. }