-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_ValidPalindrome.py
More file actions
36 lines (29 loc) · 1.26 KB
/
02_ValidPalindrome.py
File metadata and controls
36 lines (29 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Question link - https://leetcode.com/problems/valid-palindrome/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def isPalindrome(self, s: str) -> bool:
# SOl2 - uses pointer appoarch with helper func alphaNum()
l , r = 0 , len(s) - 1
while l < r:
# check left char is alphnaNum , not then increment l
while l<r and not self.alphaNum(s[l]):
l += 1
# check right char is alphnaNum ,not then decrement r
while l<r and not self.alphaNum(s[r]):
r -= 1
if s[l].lower() != s[r].lower():
return False
l , r = l + 1 , r - 1
return True
def alphaNum(self, c):
# this function checks for alphanum characters return True
return (ord('A') <= ord(c) <= ord('Z')
or ord('a') <= ord(c) <= ord('z')
or ord('0') <= ord(c) <= ord('9'))
# # Sol 1
# newStr = "" #Creating a new string
# # Traverse the string and if it is alnum then convert to lowercase
# for c in s:
# if c.isalnum():
# newStr += c.lower()
# # Return True , if palindrome otherwise false
# return newStr == newStr[::-1]