125. Valid Palindrome
- Total Accepted: 124387
- Total Submissions: 499823
- Difficulty: Easy
- Contributors: Admin
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Code
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ lp, rp = 0, len(s)-1 while lp < rp: while lp < rp and not s[lp].isalnum(): lp += 1 while lp < rp and not s[rp].isalnum(): rp -= 1 if s[lp].lower() != s[rp].lower(): return False lp += 1 rp -= 1 return True
Idea
Not much to say. First time to use string.isalnum()
.