LeetCode 125. 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.

Solution

English Version in Youtube

中文版解答Youtube Link

中文版解答Bilibili Link

class Solution {

public:
    bool isPalindrome(string s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            while (!isalpha(s[i]) && !isdigit(s[i]) && i <= j) {
                i++;
            }
            while (!isalpha(s[j]) && !isdigit(s[j]) && i <= j) {
                j--;
            }
            if (i >= j) {
                break;
            }
            if (toupper(s[i]) != toupper(s[j])) {
                return false;
            }
            
            i++;
            j--;
        }
        
        return true;
    }
    
};

Last updated