ACM POJ 2001 (Shortest Prefixes)
来源:互联网 发布:微盘今日数据 编辑:程序博客网 时间:2024/06/12 01:36
题目链接 http://poj.org/problem?id=2001
import java.util.LinkedList;import java.util.Queue;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scn = new Scanner(System.in);Trie trie = new Trie();Queue<String> queue = new LinkedList<String>();while (scn.hasNext()) {String word = scn.nextLine();queue.offer(word);trie.insert(word);}while (!queue.isEmpty()) {String word = queue.poll();System.out.println(word + " " + trie.search(word));}scn.close();}}class Trie {private Node root;public Trie() {root = new Node(new Node[26], 0);}public void insert(String word) {Node current = root;for (int i = 0; i < word.length(); ++i) {if (null != current.getChildrenItem(word.charAt(i) - 'a')) {current = current.getChildrenItem(word.charAt(i) - 'a');current.setCount(current.getCount() + 1);} else {Node newNode = new Node(new Node[26], 1);current.setChildrenItem(word.charAt(i) - 'a', newNode);current = newNode;}}}public String search(String word) {Node current = root;StringBuilder prefix = new StringBuilder();for (int i = 0; i < word.length(); ++i) {if (1 == current.getCount()) {break;}prefix.append(word.charAt(i));current = current.getChildrenItem(word.charAt(i) - 'a');}if (1 == current.getCount()) {return prefix.toString();} else {return word;}}}class Node {private Node[] children;private int count;public Node(Node[] children, int count) {this.children = children;this.count = count;}public Node getChildrenItem(int i) {return children[i];}public void setChildrenItem(int i, Node node) {children[i] = node;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}}
0 0
- ACM POJ 2001 (Shortest Prefixes)
- POJ 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes
- POJ-2001-Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ-2001-Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- poj 2001 Shortest Prefixes
- POJ-2001 Shortest Prefixes
- 如何提高服务器缓存命中率
- 一步一步学epoll同时处理海量连接的代码
- debug报错
- Cocos2d-x学习之windows 7 android环境搭建
- Java语言学习要求
- ACM POJ 2001 (Shortest Prefixes)
- 网址优化技巧要注意什么
- PHP实现队列(Queue)数据结构
- linux 物理内存读写
- 12-Linux-文件系统挂载管理
- BAT 批处理创建桌面快捷方式代码大全
- Android数据格式解析对象JSON用法
- 用jquery仿做发微博功能
- linux 搭建DHCP 服务器