hihoCoder题目AC #1014 : Trie树 Java

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		// n为词典条目数
		int n = 0;
		n = scanner.nextInt();
		// 词典
		String dictionary[] = new String[n];
		int index1 = 0;
		while (index1 < n) {
			dictionary[index1] = scanner.next();
			index1++;
		}
		// m 为查询条目数
		int m = 0;
		m = scanner.nextInt();
		// 检查词前缀
		String search[] = new String[m];
		long[] searchResult = new long[m];
		int index2 = 0;
		while (index2 < m) {
			search[index2] = scanner.next();
			index2++;
		}

		// 创建根节点
		Node rootNode = new Node('A');

		// 创建词典
		for (int index = 0; index < n; index++) {
			String dicWord = dictionary[index];
			int wordLength = dicWord.length();
			char[] dicChars = dicWord.toCharArray();
			Node tempNode = rootNode;
			// 将某一个词放入词典
			for (int innerIndex = 0; innerIndex < wordLength; innerIndex++) {
				tempNode = tempNode.getNextNode(dicChars[innerIndex]);
			}
		}

		// 使用Trie树 从search[]读取
		for (int index = 0; index < m; index++) {
			long appearCount = 0;
			String searchWord = search[index];
			int wordLength = searchWord.length();
			char[] searchChars = searchWord.toCharArray();
			Node tempNode = rootNode;
			for (int innerIndex = 0; innerIndex < wordLength; innerIndex++) {
				tempNode = tempNode.findNextNode(searchChars[innerIndex]);
				if (tempNode != null) {
					appearCount = tempNode.T;
				}
				if (tempNode == null) {
					appearCount = 0;
					break;
				}
			}

			// 储存结果
			searchResult[index] = appearCount;
			System.out.println(searchResult[index]);

		}

	}
}

class Node {

	char text;
	long T;
	Node[] nextNodeList;

	Node(char text) {
		this.text = text;
		T = 0;
		nextNodeList = new Node[26];
	}

	Node getNextNode(char c) {
		Node newNode;
		int index = c - 'a';
		if (nextNodeList[index] == null) {
			newNode = new Node(c);
			nextNodeList[index] = newNode;
			newNode.addT();
		} else {
			newNode = nextNodeList[index];
			newNode.addT();
		}
		return newNode;
	}

	void addT() {
		T++;
	}

	Node findNextNode(char c) {
		Node newNode;
		int index = c - 'a';
		if (nextNodeList[index] == null) {

			return null;
		} else {
			newNode = nextNodeList[index];
		}
		return newNode;
	}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值