Skip to content

Commit 7428ed3

Browse files
committed
add sol
1 parent da0bcfd commit 7428ed3

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

leetcode/daily/2116/sol.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/
2+
3+
package main
4+
5+
import "fmt"
6+
7+
func canBeValid(s string, locked string) bool {
8+
if len(s)%2 != 0 {
9+
return false
10+
}
11+
12+
// Forward pass
13+
balance := 0
14+
for i := 0; i < len(s); i++ {
15+
if locked[i] == '1' && s[i] == ')' {
16+
balance--
17+
} else {
18+
balance++
19+
}
20+
if balance < 0 {
21+
return false
22+
}
23+
}
24+
25+
// Backward pass
26+
balance = 0
27+
for i := len(s) - 1; i >= 0; i-- {
28+
if locked[i] == '1' && s[i] == '(' {
29+
balance--
30+
} else {
31+
balance++
32+
}
33+
if balance < 0 {
34+
return false
35+
}
36+
}
37+
38+
return true
39+
}
40+
41+
func main() {
42+
s := "))()))"
43+
locked := "010100"
44+
45+
fmt.Println(canBeValid(s, locked))
46+
}

leetcode/daily/916/sol.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// https://leetcode.com/problems/word-subsets/description/
2+
3+
package main
4+
5+
import "fmt"
6+
7+
func wordSubsets(words1 []string, words2 []string) []string {
8+
// count freq
9+
countFrequencies := func(word string) [26]int {
10+
freq := [26]int{}
11+
for _, c := range word {
12+
freq[c-'a']++
13+
}
14+
return freq
15+
}
16+
17+
// combine max words2
18+
maxFreq := [26]int{}
19+
for _, word := range words2 {
20+
freq := countFrequencies(word)
21+
for i := 0; i < 26; i++ {
22+
maxFreq[i] = max(maxFreq[i], freq[i])
23+
}
24+
}
25+
26+
result := []string{}
27+
for _, word := range words1 {
28+
freq := countFrequencies(word)
29+
isUniversal := true
30+
for i := 0; i < 26; i++ {
31+
if freq[i] < maxFreq[i] {
32+
isUniversal = false
33+
break
34+
}
35+
}
36+
if isUniversal {
37+
result = append(result, word)
38+
}
39+
}
40+
41+
return result
42+
}
43+
44+
func main() {
45+
words1 := []string{"amazon", "apple", "facebook", "google", "leetcode"}
46+
words2 := []string{"e", "o"}
47+
fmt.Println(wordSubsets(words1, words2))
48+
}

0 commit comments

Comments
 (0)