Palindrome Check

Write a function that takes in a non-empty string and that returns a boolean representing whether the string is a palindrome.

A palindrome is defined as a string that’s written the same forward and backward. Note that single-character strings are palindromes.

Solution
Loop through half of the string. Compare each character from one half to the each character from the other half.

static boolean isPalindrome(String str) {

    for (int i = 0, x = str.length() - 1; i < str.length() / 2; i++, x--) {
        if (str.charAt(x) != str.charAt(i)) {
            return false;
        }
    }

    return true;
}

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.