CC-2 : Check if String is palindrome.
Description:
Given an input String check if it is a palindrome.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
| Original String: reviver
|
IsPalindrome: true
|
| Original String: noob
|
IsPalindrome: false
|
Pseudocode:
isPalindrome(str):
| The String to be checked is received as input parameter.
|
| If str.length()==1, return true.
|
| If character at first index is not same as character at last index, return false.
|
| Recursively call method isPalindrome() after removing first and last characters of current String as first and last characters of current String have been processed above.
|
Code:
public boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
}else {
if (str.charAt(0) != str.charAt(str.length()-1)) {
return false;
}
}
return isPalindrome(str.substring(1, str.length()-1));
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionCheckPalindrome {
public boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
}else {
if (str.charAt(0) != str.charAt(str.length()-1)) {
return false;
}
}
return isPalindrome(str.substring(1, str.length()-1));
}
public static void main(String[] args) {
/***********************
Test cases given below:
**********************/
boolean retVal;
try {
RecursionCheckPalindrome rcn=new RecursionCheckPalindrome();
String str="reviver";
retVal=rcn.isPalindrome(str);
System.out.println("Original String: "+str);
System.out.println("IsPalindrome: "+retVal);
System.out.println();
str="noob";
retVal=rcn.isPalindrome(str);
System.out.println("Original String: "+str);
System.out.println("IsPalindrome: "+retVal);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}