Leetcode - 3Sum Smaller
Leetcode - Replace Words

Leetcode - Add and Search Word - Data structure design

violet posted @ Mar 28, 2020 05:26:14 AM in 算法 with tags Algorithm Golang Trie , 194 阅读

https://leetcode.com/problems/add-and-search-word-data-structure-design/

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

 

Typical trie problem.

type WordDictionary struct {
    Root *Trie
}

type Trie struct {
    Leaf bool
    Children []*Trie
    Val byte
}

/** Initialize your data structure here. */
func Constructor() WordDictionary {
    return WordDictionary {
        Root: &Trie{
            Children: make([]*Trie, 26),
        },
    }
}


/** Adds a word into the data structure. */
func (this *WordDictionary) AddWord(word string)  {
    node := this.Root
    for i := 0; i < len(word); i++ {
        index := word[i] - 'a'
        if node.Children[index] == nil {
            node.Children[index] = &Trie{
                Children: make([]*Trie, 26),
                Val: word[i],
            }
        }
        node = node.Children[index]
    }
    node.Leaf = 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 search([]byte(word), this.Root, 0)
}

func search(word []byte, node *Trie, start int) bool {    
    if start >= len(word) {
        return node.Leaf
    }

    
    if word[start] != '.' {
        //fmt.Println("next: ", node.Children[word[start]-'a'])
        if node.Children[word[start]-'a'] != nil {
            return search(word, node.Children[word[start]-'a'], start+1)
        }
    } else {
        for i := 0; i < 26; i++ {
            if node.Children[i] != nil {
                if search(word, node.Children[i], start+1) {
                    return true
                }
            }
        }
    }
    return false
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AddWord(word);
 * param_2 := obj.Search(word);
 */

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter