1185: 零起点学算法92——单词数(C)

一、题目

http://acm.wust.edu.cn/problem.php?id=1185&soj=0

二、分析

  1. 统计的是不同的单词数,即重复的单词只统计一次;
  2. 多组输入;
  3. 每行不超过1000个字符,可用一维数组读取;
  4. 输入‘#’表示结束;
  5. 文章只有小写字母和空格组成。

三、思路

用article读取整行字符串,然后依次判断每个字符,并将它们按照单词存到paper中,全部放入后,将paper的第一维,按照字符串(a-z)排序,最后在paper中,依次比较相邻的单词,相同则跳过,不同则单词数numOfWordsNoRepeat加1,最后输出单词数,并换行。

补充说明:

输入以下数据:

  a  ac  ax  a  s z ax
#
article
    a     a c     a x     a     s   z   a x     \0  
排序前paper
a \0                                                
a c \0                                              
a x \0                                              
a \0                                                
s \0                                                
z \0                                                
a x \0                                              
排序后paper
a \0                                                
a \0                                                
a c \0                                              
a x \0                                              
a x \0                                              
s \0                                                
z \0                                                

结果有5个单词。

四、代码

#include<stdio.h>
#include<string.h> // strcmp函数
#include<stdlib.h> // qsort函数
#define MAX_CHAR 1001 // 一行最大字符数
int main() {
	char article[MAX_CHAR], paper[MAX_CHAR][40]; // 保存文章
	int i, j, theWordSubscript, newWord, numOfWordsNoRepeat;
	while (gets(article) && article[0] != '#') {
		theWordSubscript = -1; // 最初没有单词,初始化下标为-1
		newWord = 1; // 是否是新单词,1是新单词,0不是新单词
		for (i = 0; article[i] != '\0'; i++) {
			if (article[i] == ' ') { // 下标为i的字符是空格
				newWord = 1; // 下个字符是新单词的首字符,newWord置1
			}
			else {
				if (newWord == 1) { // 当前字符是新单词的首字符
					theWordSubscript++; // 单词下标加1
					newWord = j = 0; // 接下来的不是新单词,newWord置0;j重置为第一个字符
				}
				paper[theWordSubscript][j++] = article[i]; // 复制当前字符到二维数组中,j自增
				paper[theWordSubscript][j] = '\0'; // 末尾赋值为结束符,表示字符串(当前单词)结束
			}
		}
		if (theWordSubscript > 0) { // 单词数(包含重复的)大于1的话,将所有单词排序a-z
			qsort(paper, theWordSubscript + 1, sizeof(char) * 40, strcmp); // 排序函数
		}
		if (theWordSubscript >= 0) { // 至少有一个单词的话,输出数据,否则输出
 			numOfWordsNoRepeat = 1; // 单词数初始化为1
			for (i = 0; i < theWordSubscript; i++) { // 统计不重复单词数
				if (strcmp(paper[i], paper[i + 1]) != 0) { // 不重复,单词数加1
					numOfWordsNoRepeat++;
				}
			}
			printf("%d\n", numOfWordsNoRepeat); // 输出单词数
		}
	}
	return 0;
}

五、截图

1185:运行截图

猜你喜欢

转载自blog.csdn.net/pfdvnah/article/details/86703802