Check if a string is a palindrome

C

palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madamracecar.

There are also numeric palindromes, including date/time stamps using short digits 11/11/11 11:11 and long digits 02/02/2020. Sentence-length palindromes ignore capitalization, punctuation, and word boundaries, so “A man, a plan, a canal, Panama!” is treated as AMANAPLANACANALPANAMA.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

Constraints:

  • s consists only of printable ASCII characters.

Solution

  • Remove all characters that is not alphanumber, e.g. ;`, . :`
  • Check if the new string equals its reverse

Kotlin implementation

#Kotlin implementation
class Solution {
    fun isPalindrome(s: String): Boolean {
        val s1 = s.toLowerCase().replace("[^a-zA-Z0-9]".toRegex(), "")
        return s1 == s1.reversed()
    }
}

For more Kotlin tutorial, go here.

Java Implementation

Check by comparing chars

 static boolean isPalindrome(String str)
    {
        // Pointers pointing to the beginning
        // and the end of the string
        int i = 0, j = str.length() - 1;
        // While there are characters toc compare
        while (i < j) {
            // If there is a mismatch
            if (str.charAt(i) != str.charAt(j))
                return false;
            // Increment first pointer and
            // decrement the other
            i++;
            j--;
        }
        // Given string is a palindrome
        return true;
    } 

About the author

Tung Nguyen

I got my bachelor of telecommunication engineering in Shanghai University, Master of IST for Paris Sud 11, and PhD from Auckland University of Technology. I am interested in combining AI/ML, Mobile and Cloud platform to build awesome applications.

Add comment

By Tung Nguyen

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Categories