C语言栈和队列实现回文单词统计
回文单词是指正序和倒序都相同的单词,比如'level'、'deified'。我们可以用栈或队列来判断一个单词是否回文,具体步骤如下:
- 将单词中的每个字符入栈或入队;
- 弹出栈或出队,将弹出的字符与单词中的对应字符比较是否相同,如果不同则说明该单词不是回文,否则继续比较;
- 如果栈或队列为空,则说明该单词是回文,统计计数。
下面是用队列实现的代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LEN 1000
int is_palindrome(char *str);
int main() {
char str[MAX_LEN];
int count = 0;
FILE *fp = fopen("text.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
while (fscanf(fp, "%s", str) != EOF) {
if (is_palindrome(str)) {
printf("%s is a palindrome.\n", str);
count++;
}
}
printf("There are %d palindrome words in the document.\n", count);
fclose(fp);
return 0;
}
int is_palindrome(char *str) {
int len = strlen(str);
char c;
int i, j;
// 将单词转换为小写
for (i = 0; i < len; i++) {
str[i] = tolower(str[i]);
}
// 判断是否回文
for (i = 0, j = len - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0;
}
}
return 1;
}
这里用了一个辅助函数is_palindrome来判断一个单词是否回文。这个函数先将单词中的每个字符转换为小写,然后用双指针的方法判断是否回文。
注意到单词中可能会出现标点符号或其他非字母字符,因此需要在读取单词之后先进行一些处理,比如转换为小写、去掉标点符号等。另外,为了避免数组越界,需要限制单词的最大长度。
原文地址: https://www.cveoy.top/t/topic/n3sC 著作权归作者所有。请勿转载和采集!