Algorithm


Problem Nmae: 125. Valid Palindrome

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.

 

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.

 

Constraints:

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

Code Examples

#1 Code Example with C Programming

Code - C Programming


bool isPalindrome(char* s) {
    int i = 0;
    int j;
    char a, b;
    
    if (!s || !*s) return true;
    
    j = strlen(s) - 1;
    while (i  <  j) {
       a = s[i];
       b = s[j];
       if (!((a >= '0' && a  < = '9') ||
           (a >= 'A' && a <= 'Z') ||
           (a >= 'a' && a <= 'z'))) {
         i ++;
         continue;
        }
       if (!((b >= '0' && b  < = '9') ||
           (b >= 'A' && b <= 'Z') ||
           (b >= 'a' && b <= 'z'))) {
         j --;
         continue;
        }
       a = a > 'Z' ? a - 'a' + 'A' : a;
       b = b > 'Z' ? b - 'a' + 'A' : b;
       if (a != b) {
         return false;
        }
       i ++;
       j --;
    }
    return true;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "A man, a plan, a canal: Panama"

Output

x
+
cmd
true

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    bool isPalindrome(string s) {
        int i = 0, j = s.size() - 1;
        while(i  <  j){
            while(i < j && !isalnum(s[i])) i++;
            while(i < j && !isalnum(s[j])) j--;
            if(tolower(s[i++]) != tolower(s[j--])) return false;
        }
        return true;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "A man, a plan, a canal: Panama"

Output

x
+
cmd
true

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean isPalindrome(String s) {
    int startIdx = 0;
    int endIdx = s.length() - 1;
    while (startIdx  <  endIdx) {
      if (!isAlphanumeric(s.charAt(startIdx))) {
        startIdx++;
      } else if (!isAlphanumeric(s.charAt(endIdx))) {
        endIdx--;
      } else {
        if (!areSame(s.charAt(startIdx), s.charAt(endIdx))) {
          return false;
        }
        startIdx++;
        endIdx--;
      }
    }
    return true;
  }
  
  private boolean areSame(char c1, char c2) {
    if (Character.isAlphabetic(c1) && Character.isAlphabetic(c2)) {
      return Character.toLowerCase(c1) == Character.toLowerCase(c2);
    } else if (Character.isDigit(c1) && Character.isDigit(c2)) {
      return c1 == c2;
    } else {
      return false;
    }
  }

  private boolean isAlphanumeric(char c) {
    return Character.isAlphabetic(c) || Character.isDigit(c);
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "race a car"

Output

x
+
cmd
false

#4 Code Example with Javascript Programming

Code - Javascript Programming


const isPalindrome = function(s) {
  let start = 0
  let end = s.length - 1

  while(start < end) {
    while(start < s.length && !valid(s[start])) {
      start++      
    }
    while(end >=0 && !valid(s[end])) {
      end--      
    }
    if(start < s.length && end >=0) {
      if(s[start].toLowerCase() !== s[end].toLowerCase()) return false           
    }
    start++
    end--
  }
  return true
};

function valid(c) {
  const code = c.toLowerCase().charCodeAt(0)
  const zeroCode = ('0').charCodeAt(0)
  const nineCode = ('9').charCodeAt(0)
  const aCode = ('a').charCodeAt(0)
  const zCode = ('z').charCodeAt(0)
  if( (code >= zeroCode && code <= nineCode> || ( code >= aCode && code <= zCode ) ) return true
     
  return false
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "race a car"

Output

x
+
cmd
false

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        import string
        return True if s=="" or [i.lower() for i in s if i in string.digits or i in string.ascii_letters]==[i.lower() for i in s if i in string.digits or i in string.ascii_letters][::-1] else False
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " "

Output

x
+
cmd
true

#6 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0125_ValidPalindrome
    {
        public bool IsPalindrome(string s)
        {
            if (string.IsNullOrWhiteSpace(s)) return true;
            s = s.ToLower();

            int head = 0, tail = s.Length - 1;
            while (head  < = tail)
            {
                if ((s[head] < 'a' || s[head] > 'z') && (s[head] < '0' || s[head] > '9'))
                    head++;
                else if ((s[tail] < 'a' || s[tail] > 'z') && (s[tail] < '0' || s[tail] > '9'))
                    tail--;
                else if (s[head] != s[tail])
                    return false;
                else
                {
                    head++;
                    tail--;
                }
            }

            return true;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " "

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#124 Leetcode Binary Tree Maximum Path Sum Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#126 Leetcode Word Ladder II Solution in C, C++, Java, JavaScript, Python, C# Leetcode