判断回文/找到所有回文

0X00 总结

判断回文

def judgePal(s):
    left, right = 0, len(s) - 1

    while left < right:
        if s[left] != s[right]: return False
        left += 1
        right -= 1

    return True

print(judgePal("a"))
print(judgePal("ab"))
print(judgePal("aba"))
print(judgePal("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))

找到所有回文

O()

def findAllPal(s):
    m = len(s)
    # 枚举中心点
    # 只有上半部分的结果
    # res 的下半部分没使用
    res = [[False] * m for _ in range(m)]

    for center in range(m):
        # 偶数长度回文
        left, right = center, center + 1
        while left > -1 and right < m:
            if s[left] != s[right]: break
            res[left][right] = True
            left, right = left-1, right+1
        # 奇数长度回文
        left, right = center, center
        while left > -1 and right < m:
            if s[left] != s[right]: break
            res[left][right] = True
            left, right = left - 1, right + 1

    return res

a = "aabb"
# 只有上半部分
print(findAllPal(a))

你可能感兴趣的:(判断回文/找到所有回文)