ACM POJ 2001 (Shortest Prefixes)

题目链接 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 queue = new LinkedList();
		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;
	}

}

你可能感兴趣的:(字典树,ACM,字符串)