|
@@ -0,0 +1,54 @@
|
|
|
+type Node struct {
|
|
|
+ IsKey bool
|
|
|
+ Children *[26]Node
|
|
|
+}
|
|
|
+
|
|
|
+type WordDictionary struct {
|
|
|
+ Root *Node
|
|
|
+}
|
|
|
+
|
|
|
+/** Initialize your data structure here. */
|
|
|
+func Constructor() WordDictionary {
|
|
|
+ return WordDictionary{&Node{}}
|
|
|
+}
|
|
|
+
|
|
|
+/** Adds a word into the data structure. */
|
|
|
+func (this *WordDictionary) AddWord(word string) {
|
|
|
+ curr := this.Root
|
|
|
+ for i := range word {
|
|
|
+ if curr.Children == nil {
|
|
|
+ curr.Children = &[26]Node{}
|
|
|
+ }
|
|
|
+ curr = &curr.Children[int(word[i]-'a')]
|
|
|
+ }
|
|
|
+ curr.IsKey = true
|
|
|
+}
|
|
|
+
|
|
|
+/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
|
|
|
+func (this *WordDictionary) Search(word string) bool {
|
|
|
+ return this.search(word, 0, this.Root)
|
|
|
+}
|
|
|
+
|
|
|
+func (this *WordDictionary) search(word string, i int, node *Node) bool {
|
|
|
+ if i == len(word) {
|
|
|
+ return node.IsKey
|
|
|
+ } else if node.Children == nil {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ if word[i] != '.' {
|
|
|
+ return this.search(word, i+1, &node.Children[int(word[i]-'a')])
|
|
|
+ }
|
|
|
+ for j := 0; j < 26; j++ {
|
|
|
+ if this.search(word, i+1, &node.Children[j]) {
|
|
|
+ return true
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * Your WordDictionary object will be instantiated and called as such:
|
|
|
+ * obj := Constructor();
|
|
|
+ * obj.AddWord(word);
|
|
|
+ * param_2 := obj.Search(word);
|
|
|
+ */
|