dengxinyi пре 6 година
родитељ
комит
a4734f109b
2 измењених фајлова са 88 додато и 0 уклоњено
  1. 59 0
      medium/677.map-sum-pairs.go
  2. 29 0
      medium/678.valid-parenthesis-string.go

+ 59 - 0
medium/677.map-sum-pairs.go

@@ -0,0 +1,59 @@
+type trie struct {
+	freq int
+	word bool
+	next [26]*trie // '26' is quite important!
+}
+
+func (t *trie) insert(key string, val int) {
+	res := t.search(key)
+	if res != nil && res.word {
+		val -= res.freq
+	}
+	for _, r := range key {
+		i := r - 'a'
+		if t.next[i] == nil {
+			t.next[i] = &trie{}
+		}
+		t = t.next[i]
+		t.freq += val
+	}
+	t.word = true
+}
+
+func (t *trie) search(key string) *trie {
+	for _, r := range key {
+		t = t.next[r-'a']
+		if t == nil {
+			break
+		}
+	}
+	return t
+}
+
+type MapSum struct {
+	tree trie
+}
+
+/** Initialize your data structure here. */
+func Constructor() MapSum {
+	return MapSum{}
+}
+
+func (this *MapSum) Insert(key string, val int) {
+	this.tree.insert(key, val)
+}
+
+func (this *MapSum) Sum(prefix string) int {
+	res := this.tree.search(prefix)
+	if res == nil {
+		return 0
+	}
+	return res.freq
+}
+
+/**
+ * Your MapSum object will be instantiated and called as such:
+ * obj := Constructor();
+ * obj.Insert(key,val);
+ * param_2 := obj.Sum(prefix);
+ */

+ 29 - 0
medium/678.valid-parenthesis-string.go

@@ -0,0 +1,29 @@
+func checkValidString(s string) bool {
+	set := make(map[int]bool) // Records ALL POSSIBLE VALID num of lb - rb
+	set[0] = true
+	for _, r := range s {
+		nset := make(map[int]bool)
+		switch r {
+		case '(':
+			for k := range set {
+				nset[k+1] = true
+			}
+		case ')':
+			for k := range set {
+				if 0 < k {
+					nset[k-1] = true
+				}
+			}
+		default:
+			for k := range set {
+				nset[k+1] = true
+				nset[k] = true
+				if 0 < k {
+					nset[k-1] = true
+				}
+			}
+		}
+		set = nset
+	}
+	return set[0] // Check if 0 is possible
+}