实现一个函数,判断字符串是否是回文。如果是则返回1,否则返回0。
时间: 2023-06-19 07:08:17 浏览: 93
以下是一个简单的 Python 实现:
```python
def is_palindrome(s):
s = s.lower() # 先将字符串转换为小写,便于比较
left, right = 0, len(s) - 1 # 定义左右指针
while left < right:
if s[left] != s[right]:
return 0 # 只要有一个字符不相等,就不是回文
left += 1
right -= 1
return 1
```
这个函数的时间复杂度是 $O(n)$,其中 $n$ 是字符串的长度。
相关问题
c语言实现一个函数,判断字符串是否是回文。如果是则返回1,否则返回0。
下面是一个简单的C语言函数,用于判断给定的字符串是否为回文:
```c
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int len = strlen(str);
int i, j;
for (i = 0, j = len - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0;
}
}
return 1;
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s is a palindrome\n", str);
} else {
printf("%s is not a palindrome\n", str);
}
return 0;
}
```
在这个函数中,我们使用了一个for循环来遍历字符串,同时比较第i个字符和第j个字符是否相等。如果存在不相等的情况,则该字符串不是回文,返回0。否则,该字符串是回文,返回1。
本题要求实现一个函数判断字符串是否是回文如果是则返回一否则返回零
好的,下面是代码实现:
```python
def is_palindrome(s):
return s == s[::-1]
```
使用方法:
```python
s = input("请输入一个字符串:")
if is_palindrome(s):
print("是回文")
else:
print("不是回文")
```
这样就可以判断字符串是否为回文了。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)