HomeLeetcode125. Valid Palindrome (String) - Leetcode Solutions

125. Valid Palindrome (String) – Leetcode Solutions

Description:

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.

Examples:

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Solution in Python:

To solve this problem, we need to determine if a given string sss is a palindrome after converting all uppercase letters to lowercase and removing all non-alphanumeric characters. Here’s a step-by-step plan:

  1. Filter the String: Remove all non-alphanumeric characters and convert the remaining characters to lowercase.
  2. Check for Palindrome: Compare the filtered string with its reverse to check if it reads the same forwards and backwards.
Python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        # Step 1: Filter the string to remove non-alphanumeric characters and convert to lowercase
        filtered_chars = [char.lower() for char in s if char.isalnum()]
        
        # Step 2: Create the filtered string
        filtered_string = ''.join(filtered_chars)
        
        # Step 3: Check if the filtered string is the same as its reverse
        return filtered_string == filtered_string[::-1]

# Example usage:
solution = Solution()
print(solution.isPalindrome("A man, a plan, a canal: Panama"))  # Output: True
print(solution.isPalindrome("race a car"))                      # Output: False
print(solution.isPalindrome(" "))                               # Output: True

Explanation:

  1. Filtering the String:
    • We use a list comprehension to iterate over each character in the string sss.
    • char.lower() converts the character to lowercase.
    • char.isalnum() checks if the character is alphanumeric (letters or numbers).
    • Only characters that pass the isalnum() check are included in the list.
  2. Creating the Filtered String:
    • We join the list of filtered characters into a single string using ''.join(filtered_chars).
  3. Checking for Palindrome:
    • We compare the filtered string with its reverse (achieved using slicing [::-1]).
    • If the filtered string is the same as its reverse, the function returns True, indicating that the string is a palindrome.
    • Otherwise, it returns False.

Solution in Javascript:

JavaScript
/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    // Step 1: Filter the string to remove non-alphanumeric characters and convert to lowercase
    let filteredChars = [];
    for (let i = 0; i < s.length; i++) {
        let char = s[i];
        if (char.match(/[a-zA-Z0-9]/)) {  // Check if the character is alphanumeric
            filteredChars.push(char.toLowerCase());
        }
    }
    
    // Step 2: Create the filtered string
    let filteredString = filteredChars.join('');
    
    // Step 3: Check if the filtered string is the same as its reverse
    let reversedString = filteredString.split('').reverse().join('');
    return filteredString === reversedString;
};

// Example usage:
console.log(isPalindrome("A man, a plan, a canal: Panama"));  // Output: true
console.log(isPalindrome("race a car"));                      // Output: false
console.log(isPalindrome(" "));                               // Output: true

Solution in Java:

Java
class Solution {
    public boolean isPalindrome(String s) {
        // Step 1: Filter the string to remove non-alphanumeric characters and convert to lowercase
        StringBuilder filtered = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                filtered.append(Character.toLowerCase(c));
            }
        }
        
        // Step 2: Create the filtered string
        String filteredString = filtered.toString();
        
        // Step 3: Check if the filtered string is the same as its reverse
        String reversedString = filtered.reverse().toString();
        return filteredString.equals(reversedString);
    }

    // Main method for testing the function
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.isPalindrome("A man, a plan, a canal: Panama"));  // Output: true
        System.out.println(solution.isPalindrome("race a car"));                      // Output: false
        System.out.println(solution.isPalindrome(" "));                               // Output: true
    }
}

Solution in C#:

C#
public class Solution {
    public bool IsPalindrome(string s) {
        // Step 1: Filter the string to remove non-alphanumeric characters and convert to lowercase
        var filteredChars = new List<char>();
        foreach (char c in s) {
            if (char.IsLetterOrDigit(c)) {
                filteredChars.Add(char.ToLower(c));
            }
        }
        
        // Step 2: Create the filtered string
        string filteredString = new string(filteredChars.ToArray());
        
        // Step 3: Check if the filtered string is the same as its reverse
        char[] charArray = filteredString.ToCharArray();
        Array.Reverse(charArray);
        string reversedString = new string(charArray);
        
        return filteredString == reversedString;
    }

    
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular