zoukankan      html  css  js  c++  java
  • 208. Implement Trie (Prefix Tree)

    class Node {
    	final static int the_maxsize = 26;
    	Node[] list = new Node[the_maxsize];
    	char data;
    	boolean isEnd = false;                                                 //用isEnd 代替isSelf  节约空间
    }
    
    class Trie {
    	Node node = new Node();
    	/** Initialize your data structure here. */
    	public Trie() {}
    
    	/** Inserts a word into the trie. */
    	public void insert(String word) {
    		Node temp = node;
    		char[] c = word.toCharArray();
    		for (int i = 0; i < c.length; i++) {
    			int loc = c[i] - 'a';
    			if (temp.list[loc] == null) {
    				temp.list[loc] = new Node();
    				temp.list[loc].data = c[i];
    			}
    			temp = temp.list[loc];
    		}
    		temp.isEnd = true;
    	}
    
    	/** Returns if the word is in the trie. */
    	public boolean search(String word) {
    		if (word == null)
    			return false;
    		Node temp = node;
    		char[] c = word.toCharArray();
    		for (int i = 0; i < c.length; i++) {
    			int loc = c[i] - 'a';
    			if (temp.list[loc] != null)  temp = temp.list[loc];
    			else return false;
    		}
    		if (temp.isEnd ) return true;
    		else return false;
    	}
    
    	/**
    	 * Returns if there is any word in the trie that starts with the given prefix.
    	 */
    	public boolean startsWith(String prefix) {
    		Node temp = node;
    		char[] c = prefix.toCharArray();
    		for (int i = 0; i < c.length; i++) {
    			int loc = c[i] - 'a';
    			if (temp.list[loc] != null)
    				temp = temp.list[loc];
    			else
    				return false;
    		}
    		return true;
    	}
    }
    
  • 相关阅读:
    android 多线程
    Uva 10881 Piotr’s Ants 蚂蚁
    LA 3708 Graveyard 墓地雕塑 NEERC 2006
    UVa 11300 Spreading the Wealth 分金币
    UVa 11729 Commando War 突击战
    UVa 11292 The Dragon of Loowater 勇者斗恶龙
    HDU 4162 Shape Number
    HDU 1869 六度分离
    HDU 1041 Computer Transformation
    利用可变参数函数清空多个数组
  • 原文地址:https://www.cnblogs.com/cznczai/p/11332208.html
Copyright © 2011-2022 走看看