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);
|
||||
*/
|
||||
31
solutions/2/q236/solution.go
Normal file
31
solutions/2/q236/solution.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package q236
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
if root == p || root == q {
|
||||
return root
|
||||
}
|
||||
|
||||
l := lowestCommonAncestor(root.Left, p, q)
|
||||
r := lowestCommonAncestor(root.Right, p, q)
|
||||
|
||||
switch {
|
||||
case l == nil && r == nil:
|
||||
return nil
|
||||
case l != nil && r != nil:
|
||||
return root
|
||||
case l != nil:
|
||||
return l
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
var _ = lowestCommonAncestor
|
||||
Loading…
Add table
Add a link
Reference in a new issue