dengxinyi 6 anni fa
parent
commit
860bb864a1

+ 20 - 0
medium/646.maximum-length-of-pair-chain.go

@@ -0,0 +1,20 @@
+type array [][]int
+
+func (a array) Len() int           { return len(a) }
+func (a array) Less(i, j int) bool { return a[i][1] < a[j][1] }
+func (a array) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+
+func findLongestChain(pairs [][]int) int {
+	if len(pairs) == 0 {
+		return 0
+	}
+	sort.Sort(array(pairs))
+	pre, cnt := pairs[0][1], 1
+	for _, p := range pairs {
+		if pre < p[0] {
+			pre = p[1]
+			cnt++
+		}
+	}
+	return cnt
+}

+ 24 - 0
medium/647.palindromic-substrings.go

@@ -0,0 +1,24 @@
+func countSubstrings(s string) int {
+	n, cnt := len(s), 0
+	if n == 0 {
+		return cnt
+	}
+	for i := range s {
+		cnt++
+		for j := 1; 0 <= i-j && i+j < n; j++ {
+			if s[i-j] == s[i+j] {
+				cnt++
+			} else {
+				break
+			}
+		}
+		for j := 1; 0 <= i-j+1 && i+j < n; j++ {
+			if s[i-j+1] == s[i+j] {
+				cnt++
+			} else {
+				break
+			}
+		}
+	}
+	return cnt
+}

+ 44 - 0
medium/648.replace-words.go

@@ -0,0 +1,44 @@
+type trie struct {
+	word bool
+	next [26]*trie
+}
+
+func (t *trie) insert(s string) {
+	for _, r := range s {
+		i := r - 'a'
+		if t.next[i] == nil {
+			t.next[i] = &trie{}
+		}
+		t = t.next[i]
+	}
+	t.word = true
+}
+
+func (t *trie) search(s string) string {
+	var sb strings.Builder
+	for _, r := range s {
+		t = t.next[r-'a']
+		if t == nil {
+			return ""
+		}
+		sb.WriteRune(r)
+		if t.word {
+			break
+		}
+	}
+	return sb.String()
+}
+
+func replaceWords(dict []string, sentence string) string {
+	var t trie
+	for i := range dict {
+		t.insert(dict[i])
+	}
+	words := strings.Split(sentence, " ")
+	for i := range words {
+		if root := t.search(words[i]); root != "" {
+			words[i] = root
+		}
+	}
+	return strings.Join(words, " ")
+}

+ 28 - 0
medium/649.dota2-senate.go

@@ -0,0 +1,28 @@
+func predictPartyVictory(senate string) string {
+	radiant, dire := make([]int, 0), make([]int, 0)
+	for i := range senate {
+		if senate[i] == 'R' {
+			radiant = append(radiant, i)
+		} else {
+			dire = append(dire, i)
+		}
+	}
+	r, d, n := len(radiant), len(dire), len(senate)
+	for r != 0 && d != 0 {
+		if radiant[0] < dire[0] {
+			dire = dire[1:]
+			d--
+			i := radiant[0] + n
+			radiant = append(radiant[1:], i)
+		} else {
+			radiant = radiant[1:]
+			r--
+			i := dire[0] + n
+			dire = append(dire[1:], i)
+		}
+	}
+	if r == 0 {
+		return "Dire"
+	}
+	return "Radiant"
+}

+ 13 - 0
medium/650.2-keys-keyboard.go

@@ -0,0 +1,13 @@
+func minSteps(n int) int {
+	dp := make([]int, n+1)
+	for i := 2; i <= n; i++ {
+		dp[i] = i
+		for j := 2; j*j <= i; j++ {
+			if i%j == 0 {
+				dp[i] = dp[i/j] + j
+				break // Smaller j can make dp[i] smaller.
+			}
+		}
+	}
+	return dp[n]
+}