顺序查找前缀↓
/*
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
*/
#include <iostream>
#include <string.h>
using namespace std;
struct node{
int num; //记录多少单词途径该节点,即多少单词拥有以该节点为末尾的前缀
node *next[26]; //26个子节点,用来代表26个不同字母 0存a ,1存b 。。。
};
node root,*newnode;
void insert(char *a, int len){
node *cur = &root; //当前结点移动到根节点
for (int n = 0; n < len; n++){//遍历串中所有字符
if (cur->next[a[n]-'a'] == NULL){//检查结点中是否含有a[n]-'a'所代表的字母
newnode = new node;
for (int i = 0; i < 26; i++)
newnode->next[i] = NULL;
newnode->num = 1;
cur->next[a[n] - 'a'] = newnode; //新建一个结点并置于当前的后一个结点
cur = newnode; //当前结点移动的新建结点;
}
else{ //如果某一结点的下一结点不为空
cur = cur->next[a[n] - 'a'];
cur->num++;
}
}
}
int find(char *a, int len){
node *cur = &root; //从根节点开始
for (int n = 0; n < len; n++){
if (cur->next[a[n] - 'a'] != NULL)
cur = cur->next[a[n] - 'a'];
else
return 0;
}
return cur->num;
}
int main(){
char c[1000];
while (cin.getline(c, 1000) && strlen(c) != 0){
insert(c, strlen(c));
}
while (cin.getline(c, 1000)){
cout << find(c, strlen(c)) << endl;
}
}
顺序查找任意位置的子串↓
/*
Sample Input
20
ad
ae
af
ag
ah
ai
aj
ak
al
ads
add
ade
adf
adg
adh
adi
adj
adk
adl
aes
5
b
a
d
ad
s
Sample Output
0
20
11
11
2
*/
#include <iostream>
#include <string>
using namespace std;
struct node
{
int num;
node *next[26];
node()
{
num = 1;
for(int i = 0; i < 26; i++)
next[i] = NULL;
}
} root;
void insert(string str)
{
node *temp = &root;
int i;
for(i = 0; i < str.length(); i++)
{
if(temp->next[str[i]-'a'] != NULL)
{
temp = temp->next[str[i]-'a'];
temp->num++;
}
else
{
temp ->next[str[i]-'a']=new node;
temp = temp->next[str[i]-'a'];
}
}
}
int searchstr(string str,node *rnode)
{
node *temp = rnode;
int i,s = 0;
if(rnode == NULL)return 0;
for(i = 0; i < str.length(); i++)
{
if(temp->next[str[i]-'a'] != NULL)
temp = temp->next[str[i]-'a'];
else
{
break;
}
}
if(i<str.length())s = 0;
else s = temp->num;
for(i = 0; i < 26; i++)
{
s+=searchstr(str,rnode->next[i]);
}
return s;
}
int main()
{
string str;
while(getline(cin,str) && str!="")
{
insert(str);
}
while(getline(cin,str))
{
cout<<searchstr(str,&root)<<endl;
}
return 0;
}