Monday, April 23, 2018

Check palindrome using recursion


  1. public class PalindromeUsingRecursionAlgorithm {
  2. public static void main(String[] args) {
  3. String s = "ABCBAd";
  4. boolean flag = isPalindrome(s);
  5. if (flag) {
  6. System.out.println("Palindrome !!");
  7. } else {
  8. System.out.println("Not a palindrome !! ");
  9. }
  10. }

  11. public static boolean isPalindrome(String s) {
  12. int length = s.length();
  13. // An empty string is considered as palindrome
  14. if (length == 0) {
  15. return true;
  16. }
  17. int startIndex = 0;
  18. int endIndex = length - 1;
  19. return palindromeRecursion(s, startIndex, endIndex);
  20. }

  21. public static boolean palindromeRecursion(String str, int s, int e) {
  22. // if there is only character
  23. if (s == e) {
  24. return true;
  25. }
  26. // if first and last character do not match
  27. if (str.charAt(s) != str.charAt(e)) {
  28. return false;
  29. }

  30. // If there are more than two characters, check if middle substring is
  31. // also palindrome or not.

  32. if (s < e + 1) {
  33. return palindromeRecursion(str, s + 1, e - 1);
  34. }
  35. return true;
  36. }
  37. }
Output: Not a palindrome !! 

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...