LeetCode 125. Valid Palindrome

Description

https://leetcode.com/problems/valid-palindrome/

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

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.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

Explanation

A palindrome, and its reverse, are identical to each other.

Python Solution

class Solution:
    def isPalindrome(self, s: str) -> bool:
            
        s = s.lower()
        
        s_forward = ""
        s_backward = ""
        
        for c in s:
            if c.isalnum():
                s_forward += c
                s_backward = c + s_backward
                
        return s_forward == s_backward
        
            
  • Time complexity: O(N).
  • Space complexity: O(N).

One Thought to “LeetCode 125. Valid Palindrome”

  1. Hi! I’ve posted my solution below. Could you tell me why for some cases I get an index out of bounds exception?

    class Solution {
    public boolean isPalindrome(String s) {

    char[] arr = s.toCharArray();
    int end = s.length() – 1;
    for(int start = 0; start = s.length()) {
    return false;
    }
    start++;
    }

    while(isLetter(arr[end]) == false) {
    if(end = ‘a’ && c = ‘A’ && c <= 'Z') {
    return true;
    }
    return false;
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *