Palindrome of String Using Recursion

Company tags: Amazon, Cisco, D-E_Shaw, Facebook.. etc.

Given a string S, check if it is palindrome or not.

Input:
The first line contains ‘T’ denoting the number of test cases. T testcases follow. Each testcase contains one lines of input. The first line contains the string S.

Output:
For each testcase, in a new line, print “YES” if it is a palindrome else “NO“. (Without the double quotes)

Constraints:
1 <= T <= 30
1 <= N <= 100

Example:
Input:
1
abba
Output:
true

Explanation:

// start and end defines the start and end index of string

boolean palindrome(char str[], int s, int e) 
{ 
    // If there is only one character 
    if (start == eend) 
        return true; 
  
    // If first and last 
    // characters do not match 
    if (str[start] != str[eend]) 
        return false; 
  
    // If there are more than  
    // two characters, check if  
    // middle substring is also  
    // palindrome or not
    if (start < end) 
        return isPalindrome(str, start + 1, end - 1); 
  
    return true; 
} 

Code:

package recursion;

import java.util.Scanner;

public class Palindrome {
	static boolean palindrome(char[] str, int s, int e) {
		
		
		if(s == e)
			return true;
		
		if(str[s] != str[e]) 
			return false;
		
		if(s < e) {
			return palindrome(str, s+1, e-1);
		}
		
		return true;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t-- != 0) {
			String str = sc.next();
			
			char[] ch = str.toCharArray();
			
			boolean ans = palindrome(ch, 0, ch.length-1);
			
			if(ans == true) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
			
		}
		
		
	}

}

Hope you guys understand the solution of to check palindrome of string in java using recursion.

For practicing the question link is given:https://practice.geeksforgeeks.org/problems/palindrome-string/0

Thanks for reading…!

Happy Coding..!

Thank You…!



Categories: HackerRank Questions, Interview, JAVA

Tags: , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: