【hihocoder】1014 : Trie树

题目懒得贴了。。

http://hihocoder.com/problemset/problem/1014


思路:

easy。。trie树。。。。不同点在于。。为了查询前缀效率更高,在该树中添加节点时,在添加过程中的节点都记录一下以该节点为父节点有多少个子节点。。。。。(说的我头都晕了,其实就是add word时,从root到新节点经过的路径上的每个节点记录值都加一)


算法:

import java.util.Scanner;

/**
 * http://hihocoder.com/problemset/problem/1014
 */
public class Main2 {

	public static void main(String[] args) {
		Main2 m = new Main2();
		m.handleInput();
	}

	private TrieNode root;

	public void handleInput() {
		root = new TrieNode();
		Scanner in = new Scanner(System.in);
		int n = 0;
		if (in.hasNext())
			n = in.nextInt();
		while (n > 0 && in.hasNext()) {
			n--;
			String s = in.next().trim();
			addWord(s);
		}

		int m = 0;
		if (in.hasNext())
			m = in.nextInt();
		while (m > 0 && in.hasNext()) {
			m--;
			String s = in.next().trim();
			System.out.println(search(s, 0, root));
		}
	}

	public void addWord(String word) {
		TrieNode p = root;
		for (int i = 0; i < word.length(); i++) {
			char key = word.charAt(i);
			if (p.nexts[key - 'a'] != null) {
				p = p.nexts[key - 'a'];
			} else {
				TrieNode t = new TrieNode(key);
				p.nexts[key - 'a'] = t;
				p = t;
			}
			if (i == word.length() - 1) {
				p.isword = true;
			}
			p.count++;
		}
	}

	public int search(String word, int i, TrieNode p) {

		if (i == word.length())
			return p.count;

		char key = word.charAt(i);

		if (p.nexts[key - 'a'] != null)
			return search(word, i + 1, p.nexts[key - 'a']);
		else
			return 0;
	}

	class TrieNode {
		// Initialize your data structure here.
		Character val;
		TrieNode nexts[] = new TrieNode[26];
		boolean isword = false;
		int count = 0;// 经过该节点的word数目

		public TrieNode(char key) {
			val = key;
		}
	}
}


你可能感兴趣的:(【hihocoder】1014 : Trie树)