在Python中,回文指的是一个字符串,正读和反读都一样的字符串。例如,字符串 "madam" 和 "racecar" 都是回文字符串。
1. 切片法:
def is_palindrome(s):
return s == s[::-1]
2. 递归法:
def is_palindrome_recursive(s):
if len(s) <= 1:
return True
if s == s[-1]:
return is_palindrome_recursive(s[1:-1])
return False
3. 迭代法:
def is_palindrome_iterative(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
使用这些方法,你可以检查任何字符串是否是回文。例如:
text = "madam"
print(is_palindrome(text)) 输出:True