关闭

LeetCode Implement Trie (Prefix Tree)

标签: javaleetcodeTrie
88人阅读 评论(0) 收藏 举报
分类:

Description:

Implement a trie with insertsearch, and startsWith methods.

Solution:

Trie树是字符串常用的一个数据结构,AC自动机也会用到。这里需要注意的是,prefix和search功能的不一样,也就要求了要在每个节点中添加一个标记,记录当前节点是否表示一个字符串的结束。

public class Trie {
	private TrieNode root;

	public Trie() {
		root = new TrieNode();
	}

	// Inserts a word into the trie.
	public void insert(String word) {
		TrieNode temp = root, next;
		int ch;
		for (int i = 0; i < word.length(); i++) {
			ch = word.charAt(i) - 'a';
			next = temp.nextNodes[ch];
			if (next == null) {
				next = new TrieNode();
				temp.nextNodes[ch] = next;
			}
			temp = next;
		}
		temp.isEnd = true;
	}

	// Returns if the word is in the trie.
	public boolean search(String word) {
		TrieNode temp = root, next;
		int ch;

		for (int i = 0; i < word.length(); i++) {
			ch = word.charAt(i) - 'a';
			next = temp.nextNodes[ch];
			if (next == null)
				return false;
			temp = next;
		}

		return temp.isEnd;
	}

	// Returns if there is any word in the trie
	// that starts with the given prefix.
	public boolean startsWith(String prefix) {
		TrieNode temp = root, next;
		int ch;

		for (int i = 0; i < prefix.length(); i++) {
			ch = prefix.charAt(i) - 'a';
			next = temp.nextNodes[ch];
			if (next == null)
				return false;
			temp = next;
		}
		return true;
	}

	public static void main(String[] args) {
		Trie t = new Trie();
		t.insert("abb");
		t.insert("c");
		System.out.println(t.search("a"));
		System.out.println(t.startsWith("a"));
	}
}

class TrieNode {
	TrieNode[] nextNodes = new TrieNode[26];
	boolean isEnd;

	TrieNode() {

	}

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61594次
    • 积分:3254
    • 等级:
    • 排名:第10408名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论