题解 | #配置文件恢复#
配置文件恢复
http://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
算是一种暴力搜素方法吧,好在问题复杂度不高,这么写也没毛病
#include<stdio.h>
char code1[4][10] =
{
"reset ",
"board ",
"reboot ",
"backplane "
};
char code2[5][10] =
{
"board ",
"add ",
"delete ",
"backplane ",
"abort "
};
void set(int *matchmap)
{
int i = 0;
for(i=0;i<6;i++)
{
matchmap[i] = 1;
}
}
void reset(int *matchmap)
{
int i = 0;
for(i=0;i<6;i++)
{
matchmap[i] = 0;
}
}
int find(char* str,char target)
{
// 找到target字符的位置并返回,如果没找到,则返回-1;
int i = 0;
while(*(str+i))
{
if(*(str+i)==target)
return i;
i++;
}
return -1;
}
int find1(int* map)
{
int i = 0;
for(i=0;i<6;i++)
{
if(map[i]==1)
return i;
}
return -1;
}
int minmatch(char *str, char *aim)
{
int i = 0;
while(str[i]!=' ' && str[i]!='\n' && str[i]!= 0 && aim[i]!=' ')
{
if(str[i]!=aim[i])
return 0;
i++;
}
return 1;
}
int match1(char *str, int * map)
{
int flag = 0;
if(minmatch(str,code1[0]))
{
map[1] = 1;
flag = 1;
}
if(minmatch(str,code1[1]))
{
map[2] = 1;
map[3] = 1;
flag = 1;
}
if(minmatch(str,code1[2]))
{
map[4] = 1;
flag = 1;
}
if(minmatch(str,code1[3]))
{
map[5] = 1;
flag = 1;
}
return flag;
}
int match2(char *str,int *map)
{
int i;
int flag = 0;
for(i=1;i<6;i++)
{
if(map[i])
{
if(!minmatch(str,code2[i-1]))
map[i] = 0;
else
flag++;
}
}
return flag;
}
int main()
{
char str[21] = {0};
int i;
int flag = -1;
int loc = -1;
int matchmap[6];
int match_num = 0;
while(fgets(str,20,stdin)!=0)
{
reset(matchmap);
flag = -1;
loc = find(str,' ');
if(loc != -1)
{
if(match1(str,matchmap))
{
match_num = match2(str+loc+1,matchmap);
if(match_num != 1)
flag = -1;
else
flag = find1(matchmap);
}
}
else
{
if(minmatch(str,code1[0]))
flag = 0;
}
switch(flag)
{
case 0: printf("reset what\n");break;
case 1: printf("board fault\n");break;
case 2: printf("where to add\n");break;
case 3: printf("no board at all\n");break;
case 4: printf("impossible\n");break;
case 5: printf("install first\n");break;
default: printf("unknown command\n");break;
}
}
return 0;
}