Valid Palindrome in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string with alphanumeric values and symbols. There are lower case and uppercase letters as well. We have to check whether the string is forming a palindrome or not by considering only the lowercase letters (uppercases will be converted into lower case), other symbols like a comma, space will be ignored.

Suppose the string is like “A Man, a Plan, a Canal: Panama”, then by considering these rules, it will be “amanaplanacanalpanama”. This is a palindrome.

To solve this, follow these steps −

  • define x = “”
  • read each character c in str −
    • if c is lowercase letter or number, then append c into x
    • else c is an uppercase letter, then simply convert it to lowercase and append after x
  • if x is a palindrome, then return True, otherwise False


Let us see the implementation to get a better understanding

 Live Demo

class Solution(object):
   def isPalindrome(self, s):
      :type s: str
      :rtype: bool
      x = ""
      diff = ord('a') - ord('A')
      for i in s:
         if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"):
         elif ord(i)>=ord('A') and ord(i)<=ord('Z'):
            i = chr(diff+ord(i))
      return x == x[::-1]
ob1 = Solution()
print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama"))


s = "A Man, a Plan, a Canal: Panama"


Published on 09-Jan-2020 11:16:47