Python判断字符串是否是回文结构

本文最后更新于 2017年5月16日 下午

​ 回文(Palindrome),就是一个序列(如字符串)正着读反着读是一样的。生物信息学上最常见的就是转录因子在DNA上的结合位点通常都是回文结构。在 Python 应该如何判断字符串?

  1. 递归

    1
    2
    3
    4
    5
    def isPalindrome(s):
    if len(s) <= 1:
    return True
    else:
    return s[0] == s[-1] and isPalindrome(s[1:-1])
  2. 循环

    1
    2
    3
    4
    5
    def isPalindrome1(s):
    for i in range(len(s))/2:
    if not s[i] == s[len(s)-i-1]:
    return False
    return True
  3. python的切片

    1
    2
    def isPalindrome2(s):
    return s == s[::-1]

    以上的实现复杂度也是O(n)的。


Python判断字符串是否是回文结构
https://yuluod.github.io/2017/05/16/Python判断字符串是否是回文结构/
作者
yuluo
发布于
2017年5月16日
许可协议