Home Java Java-tips Data Strings 96string_examples Java: Example - Palindrome test

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Example - Palindrome test
Posted on: February 18, 2008 at 12:00 AM
Java: Example - Palindrome test

Java: 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.

Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-29
Advertisement


DMCA.com