terça-feira, 24 de janeiro de 2017

Java - check if a string is a palindrome

"A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward, such as madam or kayak." Wikipedia.

Today I will show you a algorithm to find out if a string is a palindrome or not, the algorithm is pretty straightforward and does not need much explanation. It runs Big O(n) and isn't case sensitive:

If you want test cases you can visit http://www.palindromelist.net/ and test if a phrase is or isn't a palindrome.

     /**
     * Verify if the value is a palindrome. The algorithm is not case sensitive and only compare words.
     * The algorithm runs in big O(n).
     *
     * @param value that represent a palindrome
     * @return {@code value} is a palindrome
     */
    private static boolean isPalindrome(String value) {

        value = Optional.ofNullable(value).map(v -> v.replaceAll("\\W", "")).orElse("");

        if (value.isEmpty()) {
            return false;
        }

        final char[] chars = value.toCharArray();
        int length = value.length();
        for (int i = 0; i < length; i++) {

            char charI = Character.toUpperCase(chars[i]);
            char charJ = Character.toUpperCase(chars[length - i - 1]);

            if (charI != charJ) {
                return false;
            }
        }

        return true;
    }

Nenhum comentário:

Postar um comentário