string-is-palindrome
string-is-palindrome
Question: Implement a method that checks whether a string is a palindrome or not.
problem is to break the String into a char array, then comparing the chars from two ends. This algorithm runs in O(n) time.
Java
public static boolean isPalindrome(String input) {
// Break into a char array
char[] charArray = input.toCharArray();
// Compare front and end character until meet at middle
for (int i = 0, j = charArray.length-1; i < charArray.length / 2; i++, j--) {
if (charArray[i] != charArray[j])
return false;
}
return true;
}
Comments
Post a Comment