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
Example
Let us see the implementation to get a better understanding
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"):
x+=i
elif ord(i)>=ord('A') and ord(i)<=ord('Z'):
i = chr(diff+ord(i))
x+=i
#print(s)
#print(x)
return x == x[::-1]
ob1 = Solution()
print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama"))Input
s = "A Man, a Plan, a Canal: Panama"
Output
true