求一组字符串中 是否存在某个串是另一个串的前缀.
其实这题想怎么搞就怎么搞,主要是第一次用trie树,.
#include <iostream>
#include <cstdio>
using namespace std;
struct node{
int flag;
node * cld[2];
}tre[100], *root;
int cnt;
char buf[30];
void init(){
memset(tre, 0, sizeof(tre));
cnt = 0;
root = &tre[cnt++];
}
int addWord(){
int len = strlen(buf);
node * p = root;
for (int i = 0; i < len; ++i){
if(p->flag == 1)return false;
if(buf[i] == '0'){
if(p->cld[0] == 0){
p->cld[0] = &tre[cnt++];
}
p = p->cld[0];
}
if(buf[i] == '1'){
if(p->cld[1] == 0){
p->cld[1] = &tre[cnt++];
}
p = p->cld[1];
}
}
if(p->flag == 1)return 0;
p->flag = 1;
return 1;
}
int main(){
int cas = 1;
while (~scanf("%s", buf)){
init();
int f = 0;
addWord();
while (scanf("%s", buf) && buf[0] != '9'){
if(!addWord()){
f = 1;
}
}
if(f){
printf("Set %d is not immediately decodable\n", cas++);
}else{
printf("Set %d is immediately decodable\n", cas++);
}
}
return 0;
}

本文介绍了一种使用Trie树的数据结构来解决字符串集合中是否存在某个串作为另一个串的前缀的问题,并通过示例代码展示了如何构建Trie树并进行前缀检查。

745

被折叠的 条评论
为什么被折叠?



