125. Valid Palindrome

来源:互联网 发布:男士商务双肩包 知乎 编辑:程序博客网 时间:2024/06/06 02:39

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.

java

class Solution {    public boolean isPalindrome(String s) {        if (s == null || s.length() == 0 || s.length() == 1) {            return true;        }        s = s.trim().toLowerCase();        int left = 0, right = s.length() - 1;        while (left < right) {            while (left < right && !isValid(s.charAt(left))) {                left++;            }            while (left < right && !isValid(s.charAt(right))) {                right--;            }            if (left < right && s.charAt(left) != s.charAt(right)) {                return false;            }            left++;            right--;        }        return true;    }    private boolean isValid(char c) {        return Character.isLetter(c) || Character.isDigit(c);    }}


python

class Solution(object):    def isPalindrome(self, s):        """        :type s: str        :rtype: bool        """        if s == None or len(s) == 0 or len(s) == 1:            return True        s = s.lower()        left, right = 0, len(s) - 1        while left < right:            while left < right and not(s[left].isalpha() or s[left].isdigit()):                left += 1            while left < right and not(s[right].isalpha() or s[right].isdigit()):                right -= 1            if left < right and s[left] != s[right]:                return False            left += 1            right -= 1        return True