- public class PalindromeUsingRecursionAlgorithm {
- public static void main(String[] args) {
- String s = "ABCBAd";
- boolean flag = isPalindrome(s);
- if (flag) {
- System.out.println("Palindrome !!");
- } else {
- System.out.println("Not a palindrome !! ");
- }
- }
- public static boolean isPalindrome(String s) {
- int length = s.length();
- // An empty string is considered as palindrome
- if (length == 0) {
- return true;
- }
- int startIndex = 0;
- int endIndex = length - 1;
- return palindromeRecursion(s, startIndex, endIndex);
- }
- public static boolean palindromeRecursion(String str, int s, int e) {
- // if there is only character
- if (s == e) {
- return true;
- }
- // if first and last character do not match
- if (str.charAt(s) != str.charAt(e)) {
- return false;
- }
- // If there are more than two characters, check if middle substring is
- // also palindrome or not.
- if (s < e + 1) {
- return palindromeRecursion(str, s + 1, e - 1);
- }
- return true;
- }
- }
Monday, April 23, 2018
Check palindrome using recursion
Subscribe to:
Post Comments (Atom)
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...
-
Problem statement: There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neig...
-
Problem statement: Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the ...
-
Problem statement: Write a function to print spiral order traversal of a tree. For example. Input - 10 J H I A C D F E B G...
No comments:
Post a Comment