October 15, 2015 - I was bored so I went to play around with Java and solve some simple problem or exercise below to energize my playful mind.
Write   an   efficient   algorithm   to   check   if   a   string  
 is   a   palindrome.   A   string   is   a   palindrome   if   the  
 string   matches   the   reverse   of   string.
Example:   1221   is   a   palindrome   but   not   1121.
Solution:
public boolean isPalindrome(String data) {
        if (data == null) return false;
        char[] dataChars = data.toCharArray();
        if (dataChars.length < 2) {
            return false;
        }
        int leftIndex = 0, rightIndex = (dataChars.length - 1);
        while (rightIndex > leftIndex) {
            if (dataChars[leftIndex] != dataChars[rightIndex]) {
                return false;
            }
            leftIndex++;
            rightIndex--;
        }
        return true;
    }
I may be wrong but hopefully I got this right. Feel free to comment or let me know your thoughts.
 
No comments:
Post a Comment