判断一个字符串是否为回文
时间: 2023-09-08 12:14:45 浏览: 199
判断一个字符串是否为回文可以通过如下方法实现:
1. 将字符串反转后和原字符串比较,如果相同则为回文。
2. 从字符串的两端开始比较,判断对应字符是否相同,直到中间位置,如果都相同则为回文。
以下是第二种方法的 Python 实现代码:
```python
def is_palindrome(s):
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
```
使用示例:
```python
s1 = "aba"
s2 = "abc"
print(is_palindrome(s1)) # True
print(is_palindrome(s2)) # False
```
阅读全文