#125. Valid Palindrome | LeetCode Python Solution
Problem
LeetCode Problem
- Valid Palindrome
Python Solution
We will implement a solution to check if a phrase is palindrome using a while loop with two pointers.
class Solution:
def isPalindrome(self, s: str) -> bool:
# Convert all uppercase letters to lowercase
sLower = s.lower()
# Remove all non-alphanumeric characters
sAlphaNum = ""
for ch in sLower:
if ch.isalnum():
sAlphaNum += ch
# Check what we got so far
print(sAlphaNum)
# Check that it reads the same forward and backward using a while loop with two pointer technique
startPtr, endPtr = 0, len(sAlphaNum)-1
while endPtr > startPtr:
# Return early as soon as a non-match is detected
if sAlphaNum[startPtr] != sAlphaNum[endPtr]:
return False
startPtr += 1
endPtr -= 1
# If we get here, the phrase ia a palindrome
return True