博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode----208. Implement Trie (Prefix Tree)
阅读量:4113 次
发布时间:2019-05-25

本文共 1455 字,大约阅读时间需要 4 分钟。

链接:

大意:

实现前缀树(也称为字典树)。规定:所有输入字符串的字符为'a' - 'z'。例子:

思路:

真是好巧,自己之前由于无聊实现了一把字典树,于是不假思索地写了出来。具体思路可以查看:  

代码:

class Trie {    // 前缀树节点的数据结构    static class Node {        private boolean tag; // 标志当前节点是否为终点 默认为false        private Node[] children;        public Node() {            this.children = new Node[26];        }    }    // 节点内保存什么内容不重要 重要的是边上保存的信息    private Node root; // 记录树根节点    /** Initialize your data structure here. */    public Trie() {        root = new Node();    }        /** Inserts a word into the trie. */    public void insert(String word) {        Node r = root;        for (char c : word.toCharArray()) {            if (r.children[c - 'a'] == null)                r.children[c - 'a'] = new Node();            r = r.children[c - 'a'];        }        r.tag = true; // 设置当前为终点    }        /** Returns if the word is in the trie. */    public boolean search(String word) {        Node r = root;        for (char c : word.toCharArray()) {            if (r.children[c - 'a'] == null)                return false;            r = r.children[c - 'a'];        }        return r.tag;    }        /** Returns if there is any word in the trie that starts with the given prefix. */    public boolean startsWith(String prefix) {        Node r = root;        for (char c : prefix.toCharArray()) {            if (r.children[c - 'a'] == null)                return false;            r = r.children[c - 'a'];        }        return true;    }}

结果:

结论:

巧了。 

 

 

转载地址:http://daesi.baihongyu.com/

你可能感兴趣的文章
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
谷歌阅读器将于2013年7月1日停止服务,博客订阅转移到邮箱
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>
LeetCode第48题思悟——旋转图像(rotate-image)
查看>>
驱动力3.0,动力全开~
查看>>
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>
飞机换乘次数最少问题的两种解决方案
查看>>