125. Valid Palindrome

Dare2Solve

Dare2Solve

125. Valid Palindrome
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

A phrase is considered a palindrome if it reads the same forward and backward, disregarding case and non-alphanumeric characters. This means that by ignoring spaces, punctuation, and making the comparison case-insensitive, we can determine whether the given string is a palindrome. The key insight is to preprocess the string to filter out unnecessary characters and then check if the cleaned string is identical to its reverse.

Approach

  1. Preprocess the String:

    Iterate through the string s and build a new string containing only the lowercase alphanumeric characters. This can be done by checking each character and appending it to a new string if it is alphanumeric, while converting it to lowercase.

  2. Check for Palindrome:

    Once the string is preprocessed, compare it to its reverse. If the preprocessed string is the same forwards and backwards, then the original string s is a palindrome; otherwise, it is not.

Complexity

Time Complexity:

O(n), where n is the length of the string s. We iterate through the string once to build the preprocessed string and once more to check if it is a palindrome.

Space Complexity

O(n), where n is the length of the string s. We use additional space to store the preprocessed string.

Code

C++

#include <string>
#include <algorithm>

class Solution {
public:
    bool isPalindrome(std::string s) {
        // Remove non-alphanumeric characters and convert to lowercase
        std::string trimmedStr;
        for (char c : s) {
            if (std::isalnum(c)) {
                trimmedStr += std::tolower(c);
            }
        }
        std::string reversedStr = trimmedStr;
        std::reverse(reversedStr.begin(), reversedStr.end());
        return trimmedStr == reversedStr;
    }
};

Python

class Solution:
    def isPalindrome(self, s: str) -> bool:
        trimmed_str = ''.join(c.lower() for c in s if c.isalnum())
        return trimmed_str == trimmed_str[::-1]

Java

class Solution {
    public boolean isPalindrome(String s) {
        StringBuilder trimmedStr = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                trimmedStr.append(Character.toLowerCase(c));
            }}
        String forwardStr = trimmedStr.toString();
        String reversedStr = trimmedStr.reverse().toString();
        return forwardStr.equals(reversedStr);
    }
}

JavaScript

var isPalindrome = function(s) {
    let trimmedStr = s.replace(/[^a-zA-Z0-9]/g, '', "").toLowerCase()
    if (trimmedStr.split("").reverse().join("") === trimmedStr){
        return true
    }
    else{
        return false
    }
}