题解 | #简单错误记录#
简单错误记录
https://www.nowcoder.com/practice/2baa6aba39214d6ea91a2e03dff3fbeb
#include <stdio.h> #include <string.h> //循环输入每行 //用sscanf找到空格前 //用int数组保存行数(空格+1开始) //需要有一个index用来表明首次出现的顺序(可以用结构体) //提取每个地址最后一个\后的字符,并且最多保留16位(从后往前赋值,定义字符串大小为17,docname[16]='\0'不变) //先依次比较两个记录的行数,再比较两个记录的字符,若相同则index记为小的i,只输出index后面八位(若有难度也可以变成删除大i的记录) //从空格 struct Records { int index; char docname[17]; int linenum; int errortimes; }; int main() { char record[2][101]; int maxIndex = 0; int num = 0; //char docpath[99]; struct Records recordData[100]; while (gets(record[0])) { if (*record[0] == NULL) break; sscanf(record[0], "%[^ ]", record[1]); //printf("%s",record[1]); char* tmp; //int docpathnum=strlen(record[1]); //先判断文件地址>16位 if (strlen(record[1]) > 16) { tmp = record[1] + strlen(record[1]) - 16; //让tmp从record[1]的倒数第16位开始 //*tmp=*(int *)(record[1][docpathnum-1-16]); } else tmp = record[1]; //直接开始 //排掉\号 //这样子就是找到最后一个\的位置,循环次数较少 if (strchr(tmp + 1, '\\') != 0) { while ((tmp = strchr(tmp + 1, '\\')) != 0) { if (strchr(tmp + 1, '\\') == 0) { tmp += 1; break; } } } else { if (*tmp == '\\') tmp += 1; } strcpy(recordData[num].docname, tmp); sscanf(record[0] + strlen(record[1]) + 1, "%d", &recordData[num].linenum); //从这里开始判断是否与前面出现的有一样的 recordData[num].errortimes = 1; recordData[num].index = maxIndex + 1; //先赋值一个当前行号值 for (int i = 0; i < num; i++) { if (recordData[num].linenum == recordData[i].linenum) { if (strcmp(recordData[num].docname, recordData[i].docname) == 0) { recordData[num].index = recordData[i].index; recordData[num].errortimes = ++recordData[i].errortimes; break; } } } if (maxIndex < recordData[num].index) maxIndex = recordData[num].index; num++; } //根据index进行排序,算了,不排序,直接找index最大值,从index最大-8的记录开始打印,在上面循环的时候就可以找了 //为了减少循环次数,直接先定位recordData[i].index=maxIndex-7的i int beginnum = 0; if (maxIndex > 7) { for (int i = 0; i < num; i++) { if (recordData[i].index == ((maxIndex < 7) ? 0 : (maxIndex - 7))) { printf("%s %d %d\n", recordData[i].docname, recordData[i].linenum, recordData[i].errortimes); beginnum = i + 1; break; } } } for (int j = 1; j < 8 && maxIndex - j >= 0; j++) { for (int i = beginnum; i < num; i++) { if (recordData[i].index == ((maxIndex < 7) ? j : (maxIndex - 7 + j))) { printf("%s %d %d\n", recordData[i].docname, recordData[i].linenum, recordData[i].errortimes); //printf("%d %s %d %d\n",recordData[i].index,recordData[i].docname,recordData[i].linenum,recordData[i].errortimes); break; } } } return 0; }