Thursday, March 22, 2012

Can you write a palindrome function?

Can you write a palindrome function?

Yes, sure! Here is a very simple one, case sensitive, without handling special characters:

package com.blogspot.interviewqa4java;

/** © 2012 interviewqa4java.blogspot.com */
public class Palindrome {
  
    public static void main(String[] args) {
        String[] words= {"ABCBA", "ABCCBA", "AAC", "ABAB"};
        for (String word : words) {
            System.out.println("Is \'"+ word + "\' a palindrome? "+ isPalindrome(word));
        }
    }

    private static boolean isPalindrome(String word) {
        for (int i = 0, j=word.length()-1; i < (word.length() / 2); i++, j--) {
            if(word.charAt(i) != word.charAt(j)){
                return false;
            }
        }
        return true;
    }
}


Console results:
Is 'ABCBA' a palindrome? true
Is 'ABCCBA' a palindrome? true
Is 'AAC' a palindrome? false
Is 'ABAB' a palindrome? false

No comments:

Post a Comment

Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.

Give a good example!