c语言 Submit a solution for G20-Is it possible to make a palindrome Input file name: input.txt Time limit: 1 s Real time limit: 5 s Memory limit: 64M Palindrome check Read the sentence from the input.txt file and determine whether it is possible to get one word from the English letters of the sentence recorded in the file - a palindrome. The answer is printed on the standard output stream. You want to implement a logical function and apply it. is_palindrom(string) Input format A string of small English letters and spaces. No more than 1000 characters. Output format YES or NO Examples Input in input.txt kak za Output YES Input in input.txt abc Output NO Input in input.txt car race Output YES
时间: 2024-02-04 18:03:52 浏览: 128
可以使用一个函数来判断字符串是否为回文。具体实现方法如下:
- 定义一个函数is_palindrome(char s[]),用于判断字符串s是否为回文。
- 定义两个指针i和j,分别指向字符串s的头和尾。
- 分别比较i和j指向的字符是否相等,如果不相等则直接返回NO。
- 如果i和j指向的字符相等,则i向后移动一位,j向前移动一位,继续比较。
- 当i和j相遇时,表示字符串s是回文,返回YES。
具体代码实现如下:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_palindrome(char s[]) {
int i = 0, j = strlen(s) - 1;
while (i < j) {
while (!isalpha(s[i])) i++; // 找到第一个字母
while (!isalpha(s[j])) j--; // 找到最后一个字母
if (tolower(s[i]) != tolower(s[j])) return 0; // 如果不相等,返回0
i++; j--;
}
return 1;
}
int main() {
FILE *fin = fopen("input.txt", "r");
char s[1001];
fgets(s, 1001, fin); // 从文件中读取字符串
fclose(fin);
if (is_palindrome(s)) printf("YES\n"); // 判断是否为回文
else printf("NO\n");
return 0;
}
注意,为了只比较小写字母的情况,需要使用tolower()
函数将字符转换为小写字母。同时,为了忽略空格和其他非字母字符,需要使用isalpha()
函数判断字符是否为字母。
相关推荐















