dengxinyi 6 年之前
父節點
當前提交
a634d55e74
共有 2 個文件被更改,包括 82 次插入0 次删除
  1. 28 0
      medium/210.course-schedule-ii.go
  2. 54 0
      medium/211.add-and-search-word-data-structure-design.go

+ 28 - 0
medium/210.course-schedule-ii.go

@@ -0,0 +1,28 @@
+func findOrder(numCourses int, prerequisites [][]int) []int {
+	adj := make([][]int, numCourses)
+	in := make(map[int]int)
+	for i := 0; i < numCourses; i++ {
+		in[i] = 0
+	}
+	for i := range prerequisites {
+		adj[prerequisites[i][1]] = append(adj[prerequisites[i][1]], prerequisites[i][0])
+		in[prerequisites[i][0]]++
+	}
+	order := make([]int, 0)
+	for ring := true; len(in) != 0; ring = true { // Sort by the indegree of nodes
+		for k, v := range in {
+			if v == 0 {
+				ring = false
+				order = append(order, k)
+				delete(in, k)
+				for i := range adj[k] {
+					in[adj[k][i]]--
+				}
+			}
+		}
+		if ring {
+			return []int{}
+		}
+	}
+	return order
+}

+ 54 - 0
medium/211.add-and-search-word-data-structure-design.go

@@ -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);
+ */