Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Trie {
- Node root;
- /** Initialize your data structure here. */
- public Trie() {
- root = new Node();
- }
- /** Inserts a word into the trie. */
- public void insert(String word) {
- Node current = root;
- for (char c: word.toCharArray()) {
- if (current.children[c - 'a'] != null) {
- current.count++;
- } else {
- current.children[c - 'a'] = new Node();
- }
- current = current.children[c - 'a'];
- }
- current.isFinal = true;
- }
- /** Returns if the word is in the trie. */
- public boolean search(String word) {
- Node current = root;
- for (char c: word.toCharArray()) {
- if (current.children[c - 'a'] == null) {
- return false;
- }
- current = current.children[c - 'a'];
- }
- return current.isFinal;
- }
- /** Returns if there is any word in the trie that starts with the given prefix. */
- public boolean startsWith(String prefix) {
- Node current = root;
- for (char c: prefix.toCharArray()) {
- if (current.children[c - 'a'] == null) {
- return false;
- }
- current = current.children[c - 'a'];
- }
- return true;
- }
- static class Node {
- Node[] children;
- boolean isFinal;
- int count;
- public Node() {
- children = new Node[26];
- }
- }
- }
- /**
- * Your Trie object will be instantiated and called as such:
- * Trie obj = new Trie();
- * obj.insert(word);
- * boolean param_2 = obj.search(word);
- * boolean param_3 = obj.startsWith(prefix);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement