回文是指从前往后或者从后往前阅读内容都一样的字段。比如kayak,rotator等。如何判断某字符串是否为回文呢?下面列举了3种不同的算法。
算法1
翻转字符串,然后将翻转后的字符串与原始字符串比较。翻转字符串,在Python中实现如下:
def is_palindrome(s):
'''(str) -> bool
Return True if and only if s is a palidrome.
>>> is_palindrome('noon')
True
'''
return reverse(s) == s
def reverse(s):
'''(str) -> str
Return a reversed version of s.
>>> reverse('hello')
'olleh'
'''
rev = ''
# For each character in s, add that char to the beginning of rev.
for ch in s:
rev = ch + rev
return rev
算法2
将字符串分成两部分,将第二部分字符串翻转,比较第一部分字符串和翻转后的第二部分字符串。注意在将字符串分割成两半的时候,由于字符串长度可能为奇数或者偶数,所以我们使用//的取整除法,就可以得到每一半的长度。python代码实现如下:
def is_palindrome(s):
'''(str) -> bool
Return True if and only if s is a palidrome.
>>> is_palindrome('noon')
True
'''
# The number of chars in s.
n = len(s)
# Compare the first half of s to the reverse of the second half.
return s[: n // 2] == reverse(s[n - n//2 :])
def reverse(s):
'''(str) -> str
Return a reversed version of s.
>>> reverse('hello')
'olleh'
'''
rev = ''
# For each character in s, add that char to the beginning of rev.
for ch in s:
rev = ch + rev
return rev
算法3
比较第一个字母和最后一个字母,比较第2个字母和倒数第2个字母...直到到达字符串中间时停止。
def is_palindrome(s):
'''(str) -> bool
Return True if and only if s is a palidrome.
>>> is_palindrome('noon')
True
'''
i = 0
j = len(s) - 1
while i < j and s[i] == s[j]:
i = i + 1
j = j - 1
return i >= j