In this Leetcode Valid Palindrome problem solution, we have Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Leetcode Valid Palindrome problem solution


Problem solution in Python.

class Solution:
    def isPalindrome(self, s: str) -> bool:
        i = 0
        j = len(s) - 1
        while i < j:
            while i < len(s) - 1 and not s[i].isalnum():
                i += 1
                
            while j >= 1 and not s[j].isalnum():
                j -= 1
                
            if not s[i].isalnum() or not s[j].isalnum():
                return True
                
            if s[i].lower() != s[j].lower():
                print("{} ({}), {} ({})".format(s[i], i, s[j], j))
                return False
        
            i += 1
            j -= 1
        
        return True



Problem solution in Java.

public boolean isPalindrome(String s) {
    int i =0, j = s.length()-1;
    while(i<j) {
        while(i<s.length() && !isAlphaNumeric(s.charAt(i))) i++;
        while(j>=0 && !isAlphaNumeric(s.charAt(j))) j--;
        if (j>i && !compare(s.charAt(i), s.charAt(j))) {
            return false;
        }
        i++;j--;
    }
        
   return true;           
}
private boolean compare(char a, char b) {
    if (Character.isUpperCase(a)) {
        a = (char)(a + 32);
    }
    if (Character.isUpperCase(b)) {
        b = (char)(b +32);
    }
    return a == b;
}

private boolean isAlphaNumeric(char c) {
    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' ||
        c>= '0' && c <='9') {
        return true;
    }
    return false;
}


Problem solution in C++.

class Solution {
public:
    bool isPalindrome(string s) {
        string str="";
        for(int i=0; i<s.size(); i++)
        {
            if(isalpha(s[i]))
                str+=tolower(s[i]);
            else if(isdigit(s[i]))
                str+=s[i];
        }
        string rev=str;
        reverse(rev.begin(), rev.end());
        return str==rev;
        
    }
};


Problem solution in C.

bool isPalindrome(char * s){
    
    
    if (s == NULL || !strcmp(s,"")) {return true;}
    
    int i, j, k = 0;
    int count = 0;
    int len = strlen(s);
    char buffer[len];
    
    for (i = 0; i < len; i++) {
        if(isalnum(s[i])) {
            buffer[k] = tolower(s[i]);
            k++;
        }
    }

    for (i = 0; i < k; i++) {
        j = k - 1 - i;
        
        if ((buffer[i] != buffer[j]) || (i >= j)) {
            break;
        }
        count++;
    }
    
    if (count == ceil((0 + k)/2)) { return true;}
    
    return false;
}