8000 add 383 solution · reverse/awesome-golang-leetcode@34d23b4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 34d23b4

Browse files
committed
add 383 solution
1 parent c7ec27b commit 34d23b4

File tree

2 files changed

+63
-9
lines changed

2 files changed

+63
-9
lines changed

src/0383.Ransom-Note/Solution.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
import (
4+
"strings"
5+
)
6+
7+
func canConstruct(ransomNote string, magazine string) bool {
8+
for _, c := range ransomNote {
9+
idx := strings.IndexRune(magazine, c)
10+
if idx > -1 {
11+
magazine = magazine[:idx] + magazine[idx+1:]
12+
} else {
13+
return false
14+
}
15+
}
16+
return true
17+
}
18+
func canConstruct2(ransomNote string, magazine string) bool {
19+
m := make(map[rune]int)
20+
21+
for _, v := range magazine {
22+
m[v]++
23+
}
24+
for _, v := range ransomNote {
25+
if m[v] == 0 {
26+
return false
27+
}
28+
m[v]--
29+
}
30+
return true
531
}

src/0383.Ransom-Note/Solution_test.go

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,49 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
13+
input1 string
14+
input2 string
1415
expect bool
1516
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
17+
{"TestCase", "a", "b", false},
18+
{"TestCase", "aa", "ab", false},
19+
{"TestCase", "aa", "aab", true},
20+
{"TestCase", "aab", "baa", true},
1921
}
2022

2123
// 开始测试
2224
for i, c := range cases {
2325
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
24-
got := Solution(c.inputs)
26+
got := canConstruct(c.input1, c.input2)
2527
if !reflect.DeepEqual(got, c.expect) {
26-
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
27-
c.expect, got, c.inputs)
28+
t.Fatalf("expected: %v, but got: %v, with input1: %v input2: %v",
29+
c.expect, got, c.input1, c.input2)
30+
}
31+
})
32+
}
33+
}
34+
35+
func TestSolution2(t *testing.T) {
36+
// 测试用例
37+
cases := []struct {
38+
name string
39+
input1 string
40+
input2 string
41+
expect bool
42+
}{
43+
{"TestCase", "a", "b", false},
44+
{"TestCase", "aa", "ab", false},
45+
{"TestCase", "aa", "aab", true},
46+
{"TestCase", "aab", "baa", true},
47+
}
48+
49+
// 开始测试
50+
for i, c := range cases {
51+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
52+
got := canConstruct2(c.input1, c.input2)
53+
if !reflect.DeepEqual(got, c.expect) {
54+
t.Fatalf("expected: %v, but got: %v, with input1: %v input2: %v",
55+
c.expect, got, c.input1, c.input2)
2856
}
2957
})
3058
}

0 commit comments

Comments
 (0)
0