add new solutions
This commit is contained in:
parent
d798d5e8c9
commit
886b5e0a8e
34 changed files with 1164 additions and 0 deletions
63
solutions/2/q211/solution.go
Normal file
63
solutions/2/q211/solution.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
package q211
|
||||
|
||||
type TrieNode struct {
|
||||
word bool
|
||||
next [26]*TrieNode
|
||||
}
|
||||
|
||||
func (n *TrieNode) hasMatch(pattern string, offset int) bool {
|
||||
if n == nil {
|
||||
return false
|
||||
}
|
||||
if offset == len(pattern) {
|
||||
return n.word
|
||||
}
|
||||
|
||||
c := pattern[offset]
|
||||
if c != '.' {
|
||||
return n.next[toIdx(c)].hasMatch(pattern, offset+1)
|
||||
}
|
||||
|
||||
// Wildcard character
|
||||
for _, t := range n.next {
|
||||
if t != nil && t.hasMatch(pattern, offset+1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func toIdx(b byte) int8 { return int8(b - 'a') }
|
||||
|
||||
type WordDictionary struct{ root *TrieNode }
|
||||
|
||||
func Constructor() WordDictionary {
|
||||
return WordDictionary{
|
||||
root: &TrieNode{},
|
||||
}
|
||||
}
|
||||
|
||||
func (d *WordDictionary) AddWord(word string) {
|
||||
curr := d.root
|
||||
for i := range len(word) {
|
||||
c := word[i]
|
||||
idx := toIdx(c)
|
||||
if curr.next[idx] == nil {
|
||||
curr.next[idx] = &TrieNode{}
|
||||
}
|
||||
curr = curr.next[idx]
|
||||
}
|
||||
curr.word = true
|
||||
}
|
||||
|
||||
func (d *WordDictionary) Search(word string) bool {
|
||||
return d.root.hasMatch(word, 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Your WordDictionary object will be instantiated and called as such:
|
||||
* obj := Constructor();
|
||||
* obj.AddWord(word);
|
||||
* param_2 := obj.Search(word);
|
||||
*/
|
||||
Loading…
Add table
Add a link
Reference in a new issue