当前位置: 首页 > news >正文

LeetCode -- Implement Trie (Prefix Tree)

题目描述:
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.由于题目可以假设所有input均为小写字母,因此每个节点存1个字符。
2.root的val保持空
3.创建树时,不断拿去当前word[i]的字符,i∈[0,n),如果word[i]在当前node的children中找不到,就添加到children中。同时把最后一个节点标记(hasWord)为是否为单词的末尾。
4.搜索时,每次拿word[i]的字符,逐层判断即可。如果是Search,判断最后到达的字符是否标记为hasWord;如果仅仅搜索prefix,只需判断i是否到word结尾即可。






实现代码:

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;
	}


}


相关文章:

  • 2009年的3G上网卡市场,华为将会领跑
  • LeetCode -- Kth Smallest Element in a BST
  • SQL2005CLR函数扩展-环比计算
  • LeetCode -- Majority Element
  • LeetCode -- Max Points on a Line
  • ArcGIS Server Java ADF 案例教程 17
  • LeetCode -- Maximal Square
  • ArcGIS Server Java ADF 案例教程 18
  • LeetCode -- Summary Ranges
  • ArcGIS Server Java ADF 案例教程 19
  • ArcGIS Server Java ADF 案例教程 20
  • LeetCode -- Unique Paths
  • 警惕手机流氓软件的流行
  • LeetCode -- Combination Sum II
  • 学习百度、腾讯如何把产品做到极致(转载)
  • Google 是如何开发 Web 框架的
  • 【vuex入门系列02】mutation接收单个参数和多个参数
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • CentOS7简单部署NFS
  • CentOS从零开始部署Nodejs项目
  • create-react-app做的留言板
  • ERLANG 网工修炼笔记 ---- UDP
  • Fabric架构演变之路
  • HTTP中的ETag在移动客户端的应用
  • Python3爬取英雄联盟英雄皮肤大图
  • Vue2 SSR 的优化之旅
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • 从0搭建SpringBoot的HelloWorld -- Java版本
  • 分布式任务队列Celery
  • 基于组件的设计工作流与界面抽象
  • 聊聊directory traversal attack
  • 容器服务kubernetes弹性伸缩高级用法
  • 深度学习之轻量级神经网络在TWS蓝牙音频处理器上的部署
  • 通过调用文摘列表API获取文摘
  • $.ajax()方法详解
  • $GOPATH/go.mod exists but should not goland
  • (2)(2.10) LTM telemetry
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (十六)串口UART
  • (一)RocketMQ初步认识
  • (转)scrum常见工具列表
  • (转)四层和七层负载均衡的区别
  • ***linux下安装xampp,XAMPP目录结构(阿里云安装xampp)
  • **CI中自动类加载的用法总结
  • .【机器学习】隐马尔可夫模型(Hidden Markov Model,HMM)
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)
  • .NET/C# 使窗口永不激活(No Activate 永不获得焦点)
  • .NET牛人应该知道些什么(2):中级.NET开发人员
  • @AliasFor注解
  • @private @protected @public
  • [20180129]bash显示path环境变量.txt
  • [BZOJ4010]菜肴制作
  • [C#]扩展方法
  • [LeetCode] 626. 换座位