Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Last active October 15, 2017 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbonso/11b4680f20bdedec63a05cd4d084207c to your computer and use it in GitHub Desktop.
Save jsbonso/11b4680f20bdedec63a05cd4d084207c to your computer and use it in GitHub Desktop.
[Java] Palindrome Examples
/**
* 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