zoukankan      html  css  js  c++  java
  • Java for LeetCode 208 Implement Trie (Prefix Tree)

    Implement a trie with insert, search, and startsWith methods.

    Note:
    You may assume that all inputs are consist of lowercase letters a-z.

    解题思路:

    参考百度百科:Trie树

    已经给出了详细的代码:

    JAVA实现如下:

    class TrieNode {
    	// Initialize your data structure here.
    	int num;// 有多少单词通过这个节点,即节点字符出现的次数
    	TrieNode[] son;// 所有的儿子节点
    	boolean isEnd;// 是不是最后一个节点
    	char val;// 节点的值
    
    	TrieNode() {
    		this.num = 1;
    		this.son = new TrieNode[26];
    		this.isEnd = false;
    	}
    }
    
    public class Trie {
    	private TrieNode root;
    
    	public Trie() {
    		root = new TrieNode();
    	}
    
    	public void insert(String word) {
    		if (word == null || word.length() == 0)
    			return;
    		TrieNode node = this.root;
    		char[] letters = word.toCharArray();
    		for (int i = 0; i < word.length(); i++) {
    			int pos = letters[i] - 'a';
    			if (node.son[pos] == null) {
    				node.son[pos] = new TrieNode();
    				node.son[pos].val = letters[i];
    			} else {
    				node.son[pos].num++;
    			}
    			node = node.son[pos];
    		}
    		node.isEnd = true;
    	}
    
    	// Returns if the word is in the trie.
    	public boolean search(String word) {
    		if (word == null || word.length() == 0) {
    			return false;
    		}
    		TrieNode node = root;
    		char[] letters = word.toCharArray();
    		for (int i = 0; i < word.length(); i++) {
    			int pos = letters[i] - 'a';
    			if (node.son[pos] != null) {
    				node = node.son[pos];
    			} else {
    				return false;
    			}
    		}
    		return node.isEnd;
    	}
    
    	// Returns if there is any word in the trie
    	// that starts with the given prefix.
    	public boolean startsWith(String prefix) {
    		if (prefix == null || prefix.length() == 0) {
    			return false;
    		}
    		TrieNode node = root;
    		char[] letters = prefix.toCharArray();
    		for (int i = 0; i < prefix.length(); i++) {
    			int pos = letters[i] - 'a';
    			if (node.son[pos] != null) {
    				node = node.son[pos];
    			} else {
    				return false;
    			}
    		}
    		return true;
    	}
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
    
  • 相关阅读:
    SecureCRT 自定义配置
    deepin 使用笔记
    TotalCommander 使用笔记
    不同环境下MySQL 表名大小写敏感问题
    Windows / Linux 下查看文件 MD5
    设置ll命令日期格式 并友好显示文件大小
    scp 常用命令
    【C++ IO机制】stream_buf 解析
    d
    【C++ IO机制】标准IO库(C库函数)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4563990.html
Copyright © 2011-2022 走看看