Trie字符串统计

这篇文章描述了一个Java程序,使用树状数据结构来存储和操作字符串。插入方法将字符串映射到树中,而查询方法则根据输入的字符串查找其在树中的计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main{
    static int N = 100010,idx = 0;
    static int[][] son = new int[N][26];
    static int[] cnt = new int[N];  //每一个cnt[n]上代表着某个节点是否出现过,每个单词都对应唯一的一个数字
    static char[] str = new char[N];
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void insert(char[] str){
        int p = 0;  //指针先指向根节点
        for (int i = 0; i < str.length; i++) {
            int u = str[i] - 'a';   //将字符串转化成0~25的数字

            //当前指针在p这一层还没存放str[i]
            //idx不断自增,每个idx对应一个以idx结尾的单词,不会重复
            if (son[p][u] == 0) son[p][u] = ++idx;
            //如果已经创建过该节点,就让p往下走
            p = son[p][u];
        }
        //走到的终点位置,就把该位置的cnt数组+1
        cnt[p]++;
    }

    public static int query(char[] str){
        int p = 0;
        for (int i = 0; i < str.length; i++) {
            int u = str[i] - 'a';

            //搜索的过程中要是发现该点还没有被遍历过,就直接返回0
            if (son[p][u] == 0) return 0;
            p = son[p][u];
        }
        return cnt[p];
    }

    public static void main(String[] args) throws IOException {
        int n = Integer.parseInt(in.readLine());

        while (n-->0){
           String[] data = in.readLine().split(" ");
           String ch = data[1];
           if (data[0].equals("I")){
               insert(ch.toCharArray());
           } else {
               System.out.println(query(ch.toCharArray()));
           }

        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值