leetcode 125 Valid Palindrome

Java:

class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        
        int l=0, r=s.length()-1;
        while(l<=r){
            char head = s.charAt(l);
            char tail = s.charAt(r);
            //Character.isLetterOrDigit(str)  如果 str 是字母或十进制数字,则为 true;否则为 false。
            if(!Character.isLetterOrDigit(head)) l++;
            else if(!Character.isLetterOrDigit(head)) r--;
            else{
                //.toLowerCase(str) 转换为小写
                if(Character.toLowerCase(head)!=Character.toLowerCase(tail)) return false;
                l++;
                r--;
            }
        }
        return false;
    }
}

Python:

class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.lower()
        i, j = 0, len(s) -1 
        while i < j:
            if not s[i].isalnum():
                i+=1
            elif not s[j].isalnum():
                j-=1
            else:
                if s[i] is not s[j]:
                    return False
                i+=1
                j-=1
        return True

猜你喜欢

转载自blog.csdn.net/mrxjh/article/details/79724566