Advertisement
Falexom

Untitled

Apr 14th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. // Online Go compiler to run Golang program online
  2. // Print "Try programiz.pro" message
  3.  
  4. package main
  5. import "fmt"
  6.  
  7. type TrieNode struct {
  8. children [26]*TrieNode
  9. isWord bool
  10. }
  11.  
  12. type Trie struct {
  13. root *TrieNode
  14. }
  15.  
  16. func Constructor() Trie {
  17. return Trie{
  18. root: &TrieNode{},
  19. }
  20. }
  21.  
  22. func (this *Trie) Insert(word string) {
  23. current := this.root
  24. for _, letter := range word {
  25. position := letter-'a'
  26. if current.children[position] == nil {
  27. current.children[position] = new(TrieNode)
  28. }
  29. current = current.children[position]
  30. }
  31. current.isWord = true
  32. }
  33.  
  34. func (this *Trie) Search(word string) bool {
  35. current := this.root
  36. for _, letter := range word {
  37. position := letter-'a'
  38. if current.children[position] == nil {
  39. return false
  40. }
  41. current = current.children[position]
  42. }
  43.  
  44. if current != nil{
  45. return false
  46. } else {
  47. current.isWord = true
  48. return true
  49. }
  50. }
  51.  
  52. func (this *Trie) StartsWith(prefix string) bool {
  53. current := this.root
  54. for _, letter := range prefix {
  55. position := letter-'a'
  56. if current.children[position] == nil {
  57. return false
  58. }
  59. current = current.children[position]
  60. }
  61. current.isWord = true
  62. return true
  63. }
  64.  
  65.  
  66.  
  67. func main() {
  68. fmt.Println("run!")
  69. obj := Constructor()
  70. word := "apple"
  71. obj.Insert(word)
  72. out := obj.Search("apple")
  73. fmt.Println(out)
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement