建立一個字典樹,先存入單詞,再查找單詞,最后輸出具有該前綴的單詞數量。
#include<cstdio>
#include<cstdlib>
struct node
{
int cnt;
int next[26];
} T[10000010];
int t=0;
char str[20];
void Insert(char *s)
{
int i=0, p=0, temp;
while(s[i])
{
temp=s[i]-'a';
if(T[p].next[temp]==0)
{
t++;
T[p].next[temp]=t;
}
p=T[p].next[temp];
T[p].cnt++;
i++;
}
}
void Query(char *s)
{
int i=0, p=0, temp;
while(s[i])
{
temp=s[i]-'a';
if(T[p].next[temp]==0)
{
printf("0\n");
return ;
}
p=T[p].next[temp];
i++;
}
printf("%d\n",T[p].cnt);
return ;
}
int main()
{
int m, n;
scanf("%d", &n);
getchar();
while(n--)
{
gets(str);
Insert(str);
}
scanf("%d", &m);
getchar();
while(m--)
{
gets(str);
Query(str);
}
return 0;
}
核心代碼:
void Insert(char *s)
{
int i=0, p=0, temp;
while(s[i])
{
temp=s[i]-'a';
if(T[p].next[temp]==0)
{
t++;
T[p].next[temp]=t;
}
p=T[p].next[temp];
T[p].cnt++;
i++;
}
}
先判斷是否存在該前綴,如果不存在,就構建新的枝葉。
查找一個就為該枝葉記一次數,表示到該枝葉的前綴個數