Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | /* |
| 2 | Copyright 2016 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package util |
| 18 | |
| 19 | // A simple trie implementation with Add and HasPrefix methods only. |
| 20 | type Trie struct { |
| 21 | children map[byte]*Trie |
| 22 | wordTail bool |
| 23 | word string |
| 24 | } |
| 25 | |
| 26 | // NewTrie creates a Trie and add all strings in the provided list to it. |
| 27 | func NewTrie(list []string) Trie { |
| 28 | ret := Trie{ |
| 29 | children: make(map[byte]*Trie), |
| 30 | wordTail: false, |
| 31 | } |
| 32 | for _, v := range list { |
| 33 | ret.Add(v) |
| 34 | } |
| 35 | return ret |
| 36 | } |
| 37 | |
| 38 | // Add adds a word to this trie |
| 39 | func (t *Trie) Add(v string) { |
| 40 | root := t |
| 41 | for _, b := range []byte(v) { |
| 42 | child, exists := root.children[b] |
| 43 | if !exists { |
| 44 | child = &Trie{ |
| 45 | children: make(map[byte]*Trie), |
| 46 | wordTail: false, |
| 47 | } |
| 48 | root.children[b] = child |
| 49 | } |
| 50 | root = child |
| 51 | } |
| 52 | root.wordTail = true |
| 53 | root.word = v |
| 54 | } |
| 55 | |
| 56 | // HasPrefix returns true of v has any of the prefixes stored in this trie. |
| 57 | func (t *Trie) HasPrefix(v string) bool { |
| 58 | _, has := t.GetPrefix(v) |
| 59 | return has |
| 60 | } |
| 61 | |
| 62 | // GetPrefix is like HasPrefix but return the prefix in case of match or empty string otherwise. |
| 63 | func (t *Trie) GetPrefix(v string) (string, bool) { |
| 64 | root := t |
| 65 | if root.wordTail { |
| 66 | return root.word, true |
| 67 | } |
| 68 | for _, b := range []byte(v) { |
| 69 | child, exists := root.children[b] |
| 70 | if !exists { |
| 71 | return "", false |
| 72 | } |
| 73 | if child.wordTail { |
| 74 | return child.word, true |
| 75 | } |
| 76 | root = child |
| 77 | } |
| 78 | return "", false |
| 79 | } |