您的位置:首页 > 其它

UVa 10815 - Andy's First Dictionary解题报告

2014-01-27 17:20 369 查看
一道字符串处理题,结合了提取单词和排序两个方面。

题目很简单直观,但是调试起来却很麻烦。应该是我编程还不够熟练。

#include <iostream>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;

bool check(char *, int);
int cmp_string(const void* _a, const void* _b);

const int MAX = 5010;
char str[1000], s[100];
char word[MAX][100];

int main()
{
//freopen("data.txt", "r", stdin);
int count = 0;
while (cin.getline(str, 1000))
{
int m = 0;
for (int i = 0; i < strlen(str) + 1; i++)//这里的strlen没有加1,结果每句的最后一个单词无法判断@
{
if(str[0] == '\0')//跳过空行
break;
if(isalpha(str[i]))//读取每个字母
s[m++] = tolower(str[i]);
else if(isalpha(str[i - 1]))//@非字母前面的为字母,说明是一个完整的单词
{
m = 0;
if(check(s, count))//检查是否有重复
{
count++;//这里先是把count++放在了if的外层,导致word数组中间多了一些空字符,后来这句又放在了strcpy的后面,导致count-1=-1,数组越界
strcpy(word[count - 1], s);//count-1表示从0~MAX的次序
}
memset(s, 0, sizeof(s));
}
}
memset(str, 0, sizeof(str));//注意清空数组
}
qsort(word, count, sizeof(word[0]), cmp_string);//快速排序,参考刘汝佳的算法竞赛入门经典
for(int i = 0; i < count; i++)
printf("%s\n", word[i]);
return 0;
}

bool check(char * s, int count)
{
for(int i = 0; i < count; i++)
if(strcmp(word[i], s) == 0)
return false;
return true;
}

int cmp_string(const void* _a, const void* _b)
{
char* a = (char*)_a;
char* b = (char*)_b;
return strcmp(a, b);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: