LeetCode208——实现 Trie (前缀树)

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/

题目描述:

知识点:Trie、哈希表

思路:定义一个新的内部类Node,用isWord标记该位置是否是一个单词,用next指向下一个节点

insert、search和startWith操作的时间复杂度均是O(n),其中n为待插入字符串或待查询字符串或前缀的长度。

JAVA代码:

class Trie {
	private class Node{
		private boolean isWord;
		private HashMap<Character, Node> next;
		public Node(boolean isWord) {
			this.isWord = isWord;
			this.next = new HashMap<>();
		}
		public Node() {
			this(false);
		}
	}
	private Node root;
	private int size;
    public Trie() {
        root = new Node();
        size = 0;
    }
    public void insert(String word) {
    	Node cur = root;
        for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if(cur.next.get(c) == null) {
				cur.next.put(c, new Node());
			}
			cur = cur.next.get(c);
		}
        if(!cur.isWord) {
        	cur.isWord = true;
        	size++;
        }
    }
    public boolean search(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if(cur.next.get(c) == null) {
				return false;
			}
			cur = cur.next.get(c);
		}
        return cur.isWord;
    }
    public boolean startsWith(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
			char c = prefix.charAt(i);
			if(cur.next.get(c) == null) {
				return false;
			}
			cur = cur.next.get(c);
		}
        return true;
    }
}

LeetCode解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值