Thursday, October 28, 2010

Example - Palindrome test

//========================================================= isPalindrome
// This method returns 'true' if the parameter
// is a palindrome, a word that is spelled the
// same both forwards and backwards, eg, radar.

public static boolean isPalindrome(String word) {
int left = 0; // index of leftmost unchecked char
int right = word.length() -1; // index of the rightmost

while (left < right) {
// continue until they reach center
if (word.charAt(left) != word.charAt(right)) {
return false;// if chars are different, finished
}
left++; // move left index toward the center
right--; // move right index toward the center
}

return true; // if finished, all chars were same
}

This method uses two indexes that point to the left and right ends of the string. You could also write this with a for loop that goes only to the middle.

No comments:

Post a Comment

Chitika