Palindrome String check can also be implemented recursively in Java. This recursive implementation is not efficient as the iterative one because it calls String.substring() subsequently.
package basics; public class StringUtils { public static boolean isPalindrome( String str ) { int sLength = str.length(); if ( sLength < 2) { return true; } else if ( str.charAt(0) != str.charAt( sLength-1 ) ) { return false; } else if ( sLength == 2 ) { return true; } else { return isPalindrome( str.substring( 1, sLength-1 )); } } public static void main(String[] args) { String str = "madam"; boolean result = isPalindrome(str); System.out.println(str+" is Palindrome = "+result); str = "qqaacc"; result = isPalindrome(str); System.out.println(str+" is Palindrome = "+result); str = "cocoococ"; result = isPalindrome(str); System.out.println(str+" is Palindrome = "+result); } }
Create a StringUtils.java file in your workspace.
When the main method inside the StringUtils class executed it is going to print :
madam is Palindrome = true
qqaacc is Palindrome = false
cocoococ is Palindrome = true
If sLength == 2, then how it is a palindrome? I am confused.
ReplyDeleteThis if statement is part of the "else-if" code block. Code is not directly checking for the length of the stringLength==2 to make a decision. After passing above else-if statement, if the length of the current string is 2 then it becomes a palindrome. You can debug it with String variables "aa" and "ab" to see the difference.
ReplyDelete