poj 3630 初级Trie的应用

本文介绍了一个简单的Trie树应用案例——检查电话号码列表中是否存在一个号码是另一个号码的前缀。通过构建Trie树实现高效查询,并讨论了Trie树的基本概念及其在减少查询时间复杂度方面的优势。

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

这是一道trie的简单应用题。题意是判断给的那个电话列表里面是否存在一个电话号码是另一个电话号码的前缀,存在输出:NO,不存在

输出YES。

下面简单的介绍下Trie树(多叉树),又称字典树,单词查找树。它的思想就是用空间换时间,利用公共前缀我减少查询的时间复杂度,它还有一个优点就是插入和查询可以并行抄作。查询的时间复杂度是:要查找的单词或者说是字符串的长度length。

import java.util.Scanner; public class Main { private static Trie trie = new Trie(); private static boolean isConsistent = true; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; ++i) { int n = sc.nextInt(); sc.nextLine(); trie = new Trie(); isConsistent = true; for (int j = 0; j < n; ++j) { String phone = sc.nextLine(); if (isConsistent) buildTrie(phone); } if (isConsistent) System.out.println("YES"); else System.out.println("NO"); } } static void buildTrie(String s) { // char[] c = s.toCharArray(); int len = s.length(); Trie tmpTrie = trie; for (int i = 0; i < len; ++i) { int ch = Integer.parseInt(s.substring(i, i + 1)); // System.out.println(ch+"---"+(int)ch); Trie tmp = tmpTrie.next[ch]; if (tmp == null) { tmp = new Trie(); tmp.node = 1; if (i == len - 1) tmp.isDispear = true;// 表示这是一个电话的结尾 tmpTrie.next[ch] = tmp; tmpTrie = tmp; } else { if (tmp.isDispear) { isConsistent = false; break; } if (i == len - 1) { isConsistent = false; break; } tmpTrie = tmp; } } } private static class Trie { int node = 0; boolean isDispear = false;//是否是某个电话号码的最后一个 Trie[] next = new Trie[10]; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值