1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Trie { static class Node{ boolean end =false; Node []son =new Node[26]; } Node root =new Node(); public Trie() { } public void insert(String word) { Node curr =root; for(char arr:word.toCharArray()){ arr -='a'; if(curr.son[arr] == null){ curr.son[arr] =new Node(); } curr = curr.son[arr]; } curr.end =true; } public boolean search(String word) { return getTrie(word)==2; } public boolean startsWith(String prefix) { return getTrie(prefix)!=0; } int getTrie(String word){ Node arr =root; for(char now:word.toCharArray()){ now-='a'; if(arr.son[now]==null){ return 0; } arr = arr.son[now]; } return arr.end == true?2:1; } }
|