Last active
October 15, 2017 01:14
-
-
Save jsbonso/11b4680f20bdedec63a05cd4d084207c to your computer and use it in GitHub Desktop.
[Java] Palindrome Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Check if the given input is a Palindrome | |
* using a StringBuilder. | |
* @author Jon Bonso | |
* @param input | |
* @return boolean | |
*/ | |
private static boolean isPalindrome(String input) { | |
return input.equals(new StringBuilder(input).reverse().toString()); | |
} | |
/** | |
* Check if the given input is a Palindrome | |
* using a good old character array iteration | |
* @param input | |
* @author Jon Bonso | |
* @return boolean | |
*/ | |
private static boolean isPalindromeV2(String input) { | |
char[] inputArray = input.toCharArray(); | |
int endIndex = inputArray.length - 1; | |
int ctr = 0; | |
// Loop only through the middle of the array | |
while( ctr < (endIndex/2) ) { | |
// As you move to the middle, check if the current character | |
// is not the same with the character on the other end of the array. | |
if (inputArray[ctr] != inputArray[endIndex - ctr]) { | |
// If it is, the the input is not a palindrom, hence, return false | |
return false; | |
} | |
ctr++; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment