- 题目描述:
-
给出一个长度不超过1000的字符串,判断它是不是回文(顺读,逆读均相同)的。
- 输入:
-
输入包括一行字符串,其长度不超过1000。
- 输出:
-
可能有多组测试数据,对于每组数据,如果是回文字符串则输出"Yes!”,否则输出"No!"。
- 样例输入:
-
hellolleh helloworld
- 样例输出:
-
Yes! No!
下面请看程序:
#include <stdio.h> #include <string.h> int main() { char s[100]; int i,j; int a=1; while(true) { scanf("%s",&s); for(i=0,j=strlen(s)-1;i<=j;i++,j--) { if (s[i]!=s[j]) //有一个不同则a变为0,跳出循环 a=0; break; } if(a) printf("yes\n"); else printf("no\n"); } return 0; }
方法二:
#include <stdio.h> #include <string.h> int main() { char s[100]; int i,j; int a=0; scanf("%s",&s); for(i=0,j=strlen(s)-1;i<=j;i++,j--) { if (s[i]==s[j]) a++; } if(a==(strlen(s)+1)/2) printf("yes"); //判断a的大小是否等于字符串加1的一半 else printf("no"); return 0; }
程序截图:
最后我们看一下用python来解决这道题目的代码:
while True: try: a = input() print("Yes!" if a==a[::-1] else "No!") # 切片操作,不会的科普一下 except: break