重囗另类BBWSeⅹHD,av狼论坛,精品一卡2卡三卡4卡乱码理论,体育生gv老师浪小辉3p警察

LeetCode Implement Trie (Prefix Tree) -電腦資料

電腦資料 時(shí)間:2019-01-01 我要投稿
【www.ipr-jzsc.com - 電腦資料】

    題目描述:

    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.

    思路:

    1.由于題目可以假設(shè)所有input均為小寫(xiě)字母,因此每個(gè)節(jié)點(diǎn)存1個(gè)字符,

LeetCode Implement Trie (Prefix Tree)

    2.root的val保持空

    3.創(chuàng)建樹(shù)時(shí),不斷拿去當(dāng)前word[i]的字符,i∈[0,n),如果word[i]在當(dāng)前node的children中找不到,就添加到children中。同時(shí)把最后一個(gè)節(jié)點(diǎn)標(biāo)記(hasWord)為是否為單詞的末尾。

    4.搜索時(shí),每次拿word[i]的字符,逐層判斷即可。如果是Search,判斷最后到達(dá)的字符是否標(biāo)記為hasWord;如果僅僅搜索prefix,只需判斷i是否到word結(jié)尾即可。

    實(shí)現(xiàn)代碼:

   

public class TrieNode {    // Initialize your data structure here.    public TrieNode() {		children = new List<trienode>();		hasWord = false;    }	public TrieNode(char v){		val = v;		children = new List<trienode>();		hasWord = false;	}		public IList<trienode>children;	public char val;	public bool hasWord ;}public class Trie {    public TrieNode root;    public Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    public void Insert(String word) {		if(string.IsNullOrEmpty(word)){			return;		}		var n = root;		var index = 0;				// try find		while(n.children.Count > 0 && index < word.Length){			var first = n.children.FirstOrDefault(x=>x.val == word[index]);			if(first != null){				n = first;				index++;			}			else{				break;			}		}		if(index < word.Length){			// if not exist , create new node			for(var i = index; i < word.Length; i++){				var child = new TrieNode(word[i]);				n.children.Add(child);				n = child;			}		}		n.hasWord = true;		    }    // Returns if the word is in the trie.    public bool Search(string word) {		TrieNode n = null;		var index = TryFindNode(word, out n);		return index == word.Length && n.hasWord;    }	    // Returns if there is any word in the trie    // that starts with the given prefix.    public bool StartsWith(string word) {		TrieNode n = null;		var index = TryFindNode(word, out n);		return index == word.Length;    }		private int TryFindNode(string word, out TrieNode node){		var n = root;				var index = 0;		while(n.children.Count > 0 && index < word.Length){			var first = n.children.FirstOrDefault(x => x.val == word[index]);			if(first != null){				n = first;				index++;			}			else{				break;			}		}				node = n;;		return index;	}}</trienode></trienode></trienode>

最新文章
主站蜘蛛池模板: 陇川县| 永登县| 始兴县| 崇左市| 余干县| 柏乡县| 兴隆县| 洪泽县| 大港区| 金山区| 大理市| 台东市| 鄂伦春自治旗| 洱源县| 贵阳市| 合水县| 尼木县| 宁德市| 保德县| 麻江县| 四平市| 碌曲县| 邻水| 平塘县| 天镇县| 凤山市| 仙居县| 渝北区| 苍南县| 白玉县| 吉木萨尔县| 鹤峰县| 新闻| 天气| 来安县| 开平市| 通城县| 达拉特旗| 河源市| 虞城县| 福鼎市|