ACM POJ 2001 (Shortest Prefixes)
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;
	}
}
  이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
poj2630Phone List (정적 트 라이 트 리)이 문 제 는 항 저 우 전기 1671 과 마찬가지 로 - > 자세 한 내용 은 여 기 를 찌 르 세 요 < - 그래서 1671 의 코드 로 한 통 을 제출 했 는데 결국 TLE 가 되 었 습 니 다.과감하게 정적 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.