python实现回文算法
时间: 2024-07-02 14:00:23 浏览: 160
在Python中,实现回文算法可以通过几种不同的方法来完成,常见的有直接比较字符串前半部分和后半部分(反转后半部分),或者使用双指针从两端向中间遍历。这里提供两种简单的实现:
- 直接比较法: ```python def is_palindrome(s): return s == s[::-1]
测试
s = "madam" print(is_palindrome(s)) # 输出: True
2. **双指针法**:
```python
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
# 测试
s = "abccba"
print(is_palindrome(s)) # 输出: True
这两种方法都用于检查一个字符串是否是回文。
相关推荐

















