文章

1

粉丝

35

获赞

3

访问

836

头像
前缀字符串 题解:构建前缀树做法C++
P1098 中山大学2018年机试
发布于2023年7月29日 13:13
阅读数 836

构建前缀树做法

#include "iostream"
#include "cstdio"
#include "cstring"
using namespace std;

struct Node{
    int count;
    Node* child[26];
    Node(){
        count=0;
        memset(child, 0,sizeof(child));
    }
};

//字符串加入前缀树中
void insertTree(string s,Node* root){
    if(s.empty()){
        root->count++;
        return;
    }
    if(root->child[s[0]-'a']== nullptr){
        root->child[s[0]-'a']=new Node();
        insertTree(s.substr(1),root->child[s[0]-'a']);
    } else{
        insertTree(s.substr(1),root->child[s[0]-'a']);
    }
}

int ans;
//深度优先遍历找叶节点
void DFS(Node*root){
    bool flag= false;
    for (int i = 0; i < 26; ++i) {
        if(root->child[i]!= nullptr){
            flag= true;
            DFS(root->child[i]);
        }
    }
    if(!flag){
        ans++;
    }
}

int main(){
    int n;
    string s;
    while (cin>>n){
        if (n==0)break;
        Node*root=new Node();
        w...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发