#1014 : Trie树

1、用java写字典树,soeasy。。

2、nextInt()方法会读取下一个int型标志的token.但是焦点不会移动到下一行,仍然处在这一行上。当使用nextLine()方法时会读取改行剩余的所有的内容,包括换行符,然后把焦点移动到下一行的开头。所以这样就无法接收到下一行输入的String类型的变量。需要用scanner.nextline()吃掉一个换行符!!!

3、英文字母有26个!26个!26个!!!(为毛一开始我鬼迷心窍的写成了24!!!!《#1014 : Trie树》《#1014 : Trie树》《#1014 : Trie树》


import java.util.Scanner;


class trie{
	trie[] next = new trie[26];
	int cnt;
}
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		trie head = new trie();
		scanner.nextLine();
		String lineString;
		for (int i = 0; i < n; i++) {
			lineString = scanner.nextLine();
			createTrie(head, lineString);
		}
		
		int m = scanner.nextInt();
		scanner.nextLine();
		for (int i = 0; i < m; i++) {
			lineString = scanner.nextLine();
			System.out.println(searchTrie(head, lineString));
		}
	}

	private static int searchTrie(trie head, String lineString) {
		// TODO Auto-generated method stub
		trie p = head;
		for (int j = 0; j < lineString.length(); j++) {
			char tmp = lineString.charAt(j);
			if (p.next[tmp - 'a'] != null) {
				p = p.next[tmp - 'a'];
			}
			else {
				return 0;
			}
		}
		return p.cnt;
	}

	private static void createTrie(trie head, String lineString) {
		// TODO Auto-generated method stub

		trie p = head;
		for (int j = 0; j < lineString.length(); j++) {
			char tmp = lineString.charAt(j);
			if (p.next[tmp - 'a'] != null) {
				p = p.next[tmp - 'a'];
				p.cnt++;
			}
			else {
				trie node = new trie();
				p.next[tmp-'a'] = node;
				p = node;
				p.cnt = 1;
			}
		}
		
	}

}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/u011860731/article/details/48373423
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注