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

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

Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Java代码:

class TrieNode {    private final int R = 26;    private final TrieNode[] children;    private String item;    public TrieNode() {        children = new TrieNode[R];        item = "";    }    public String getItem() {        return item;    }    public void setItem(String item) {        this.item = item;    }    public TrieNode[] getChildren() {        return children;    }    public TrieNode getChild(int i) {        if (i >= 26 || i < 0) throw new IllegalArgumentException();        return children[i];    }    public void setChild(int i, TrieNode node) {        children[i] = node;    }}public class Trie {    private TrieNode root;    public Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    public void insert(String word) {        TrieNode curr = root;        for (char c : word.toCharArray()) {            if (curr.getChild(c - 'a') == null) curr.setChild(c - 'a', new TrieNode());            curr = curr.getChild(c - 'a');        }        curr.setItem(word);    }    // Returns if the word is in the trie.    public boolean search(String word) {        TrieNode curr = root;        for (char c : word.toCharArray()) {            if (curr.getChild(c - 'a') == null) return false;            curr = curr.getChild(c - 'a');        }        return curr.getItem().equals(word);    }    // Returns if there is any word in the trie    // that starts with the given prefix.    public boolean startsWith(String prefix) {        TrieNode curr = root;        for (char c : prefix.toCharArray()) {            if (curr.getChild(c - 'a') == null) return false;            curr = curr.getChild(c - 'a');        }        return true;    }}// Your Trie object will be instantiated and called as such:// Trie trie = new Trie();// trie.insert("somestring");// trie.search("key");
 

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

你可能感兴趣的文章
hd disk / disk raid / disk io / iops / iostat / iowait / iotop / iometer
查看>>
project ASP.NET
查看>>
db db2_monitorTool IBM Rational Performace Tester
查看>>
OS + Unix Aix telnet
查看>>
IBM Lotus
查看>>
Linux +Win LAMPP Tools XAMPP 1.7.3 / 5.6.3
查看>>
my read_university
查看>>
network manager
查看>>
OS + Linux Disk disk lvm / disk partition / disk mount / disk io
查看>>
RedHat + OS CPU、MEM、DISK
查看>>
net TCP/IP / TIME_WAIT / tcpip / iperf / cain
查看>>
webServer kzserver/1.0.0
查看>>
OS + Unix IBM Aix basic / topas / nmon / filemon / vmstat / iostat / sysstat/sar
查看>>
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
linux下安装django
查看>>
Android 解决TextView设置文本和富文本SpannableString自动换行留空白问题
查看>>
Android开发中Button按钮绑定监听器的方式完全解析
查看>>
Android自定义View实现商品评价星星评分控件
查看>>
postgresql监控工具pgstatspack的安装及使用
查看>>