CCF-CSP题解 201803-3 URL映射
题目要求写一个简易的URL规则和URL地址匹配的程序。
说说我的思路。
将URL规则和地址都截成片段用结构体\(<type, str[]>\)存储。对于URL规则,\(type\)为0代表\(/\),1代表\(<str>\),2代表\(<int>\),3代表\(<path>\),4代表两个\(/\)之间的字符串(用\(str[]\)存储)。对于URL地址,\(type\)为0代表\(/\),1代表两个\(/\)之间的字符串(用\(str[]\)存储)。
然后就是一些字符串处理,模拟着匹配一下。不同\(type\)的节点匹配起来有些不同。
注意\(<int>\)匹配后输出,要去掉前导零。
#include <bits/stdc++.h>
const int maxn = 100;
const int maxm = 100;
using namespace std;
struct tNode
{
int type;
char str[105];
};
tNode rule[maxn+5][55];
int ruleCnt[maxn+5];
char name[maxn+5][105];
tNode url[55];
int urlCnt;
bool isNumber(char s[])
{
for (int i = 0; s[i] != '\0'; i++)
{
if (s[i] < '0' || s[i] > '9')
return false;
}
return true;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
memset(ruleCnt, 0, sizeof(ruleCnt));
for (int i = 1; i <= n; i++)
{
char p[105], r[105];
scanf("%s%s", p, r);
int &cnt = ruleCnt[i];
for (int j = 0; p[j] != '\0'; )
{
if (p[j] == '/')
{
rule[i][++cnt].type = 0;
j++;
}
else if (p[j] == '<')
{
if (p[j+1] == 's')
{
rule[i][++cnt].type = 1;
j += 5;
}
else if (p[j+1] == 'i')
{
rule[i][++cnt].type = 2;
j += 5;
}
else
{
rule[i][++cnt].type = 3;
j += 6;
}
}
else
{
rule[i][++cnt].type = 4;
int k = 0;
for (; p[j] != '/' && p[j] != '\0'; j++)
{
rule[i][cnt].str[k++] = p[j];
}
rule[i][cnt].str[k] = '\0';
}
}
strcpy(name[i], r);
}
while (m--)
{
char q[105];
scanf("%s", q);
urlCnt = 0;
int &cnt = urlCnt;
for (int i = 0; q[i] != '\0'; )
{
if (q[i] == '/')
{
url[++cnt].type = 0;
i++;
}
else
{
url[++cnt].type = 1;
int k = 0;
for (; q[i] != '/' && q[i] != '\0'; i++)
{
url[cnt].str[k++] = q[i];
}
url[cnt].str[k] = '\0';
}
}
bool fflag = false;
for (int i = 1; i <= n; i++)
{
bool flag = true;
int ansPath = 0;
if (ruleCnt[i] > urlCnt)
flag = false;
if (ruleCnt[i] < urlCnt && rule[i][ruleCnt[i]].type != 3)
flag = false;
for (int j = 1; j <= ruleCnt[i] && flag; j++)
{
if (rule[i][j].type == 0)
{
if (url[j].type != 0)
flag = false;
}
else if (rule[i][j].type == 1)
{
if (url[j].type != 1)
flag = false;
}
else if (rule[i][j].type == 2)
{
if (url[j].type != 1 || !isNumber(url[j].str))
flag = false;
}
else if (rule[i][j].type == 3)
{
ansPath = j;
}
else
{
if (strcmp(rule[i][j].str, url[j].str) != 0)
flag = false;
}
}
if (flag)
{
fflag = true;
printf("%s", name[i]);
for (int j = 1; j <= ruleCnt[i]; j++)
{
if (rule[i][j].type == 1)
printf(" %s", url[j].str);
else if (rule[i][j].type == 2)
{
int k = 0;
for (; url[j].str[k] == '0'; k++);
if (url[j].str[k] == '\0')
printf(" 0");
else
printf(" %s", url[j].str + k);
}
else if (rule[i][j].type == 3)
{
printf(" ");
for (int k = ansPath; k <= urlCnt; k++)
{
if (url[k].type == 0)
printf("/");
else if (url[k].type == 1)
printf("%s", url[k].str);
}
}
}
printf("\n");
break;
}
}
if (!fflag)
printf("404\n");
}
return 0;
}