力扣--125验证回文串/680验证回文字符串II

125验证回文串

力扣--125验证回文串/680验证回文字符串II_第1张图片

python代码

常规

def isPalindrome(s):
    if len(s) < 2:
        return True
    sList = []
    s = s.lower()
    print(s)
    for word in s:
        if word.isalnum():
            sList.append(word)
    n=len(sList)//2
    if sList[:n]==sList[::-1][:n]:
        return True
    else:
        return False

双指针

def isPalindrome(s):
    if len(s) < 2:
        return True
    s = s.lower()
    left = 0
    right = len(s) - 1
    while right - left  > 0: 
        if not s[left].isalnum():
            left += 1
            continue
        if not s[right].isalnum():
            right -= 1
            continue
        if s[left] == s[right]:
            left += 1
            right -= 1
        else:
            return False
    return True

680验证回文字符串II

力扣--125验证回文串/680验证回文字符串II_第2张图片

python 代码

def validPalindrome(s):
    isPalindrome = lambda x: x == x[::-1]
    left, right = 0, len(s) - 1
    while left <= right:
        if s[left] == s[right]:
            left += 1
            right -= 1
        else:
            return isPalindrome(s[left + 1: right + 1]) or/
             isPalindrome(s[left: right])
    return True

你可能感兴趣的:(数据结构与算法,python,leetcode,字符串)