一道简单的字符串匹配题,一开始我理解错了题目,并且一直runtime error。
最后才发现其实是题目被我复杂化了,而且错误是数组越界。
两个深刻的教训:
一是认真审题
二是变量和数组一定要初始化
最后才发现其实是题目被我复杂化了,而且错误是数组越界。
两个深刻的教训:
一是认真审题
二是变量和数组一定要初始化
三是循环最后记得把数据清零,不然会影响下面的测试
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
char codes[100][200], str[200];
bool check(int);//检查是否可快速解码
int cmp_len(const void*, const void*);
bool cmp_codes(char *, char *);//比较两个码是否有重复部分
int main()
{
//freopen("data.txt", "r", stdin);
int i = 0, count = 1;
int num = 0;
while (scanf("%s", str) == 1)
{
if(str[0] != '9')
{
strcpy(codes[i++], str);
num++;
continue;
}
else
{
if(check(num))
printf("Set %d is immediately decodable\n", count++);
else
printf("Set %d is not immediately decodable\n", count++);
num = 0;//
i = 0;//i忘了清零,结果数组越界,错了好多次
}
}
return 0;
}
bool check(int num)
{
qsort(codes, num, sizeof(codes[0]), cmp_len);//按字符长度排序
for(int i = 0; i < num; i++)
for(int j = i + 1; j < num; j++)
if(cmp_codes(codes[i], codes[j]))//如果有重复部分
return false;
return true;
}
int cmp_len(const void *_a, const void *_b)
{
char* a = (char *)_a;
char* b = (char *)_b;
return strlen(a) - strlen(b);
}
bool cmp_codes(char *a, char *b)
{
char s[200];
memset(s, 0, 200);
int m = 0;
for(int i = 0; i < strlen(a); i++)
s[m++] = b[i];//把b中与a同样长度的码提取出来
if(strcmp(a, s) == 0)
return true;
else
return false;
}