Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit a04304f

Browse files
committed
926 accepted. 4ms > 0ms
1 parent 5acf7ce commit a04304f

File tree

4 files changed

+218
-36
lines changed

4 files changed

+218
-36
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [926. Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/)
2+
3+
A string of `0`s and `1`s is monotone increasing if it consists of some number of `0`s (possibly 0), followed by some number of `1`s (also possibly 0.)
4+
5+
We are given a string `S` of `0`s and `1`s, and we may flip any `0` to a `1` or a `1` to a `0`.
6+
7+
Return the minimum number of flips to make `S` monotone increasing.
8+
9+
Example 1:
10+
11+
```text
12+
Input: "00110"
13+
Output: 1
14+
Explanation: We flip the last digit to get 00111.
15+
```
16+
17+
Example 2:
18+
19+
```text
20+
Input: "010110"
21+
Output: 2
22+
Explanation: We flip to get 011111, or alternatively 000111.
23+
```
24+
25+
Example 3:
26+
27+
```text
28+
Input: "00011000"
29+
Output: 2
30+
Explanation: We flip to get 00000000.
31+
```
32+
33+
Note:
34+
35+
1. `1 <= S.length <= 20000`
36+
1. `S` only consists of `0` and `1` characters.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package problem0926
2+
3+
func minFlipsMonoIncr(S string) int {
4+
size := len(S)
5+
6+
ones := make([]int, 0, size)
7+
zeros := make([]int, 0, size)
8+
9+
for i := 0; i < size; i++ {
10+
if S[i] == '1' {
11+
ones = append(ones, i)
12+
} else {
13+
zeros = append(zeros, i)
14+
}
15+
}
16+
17+
oneSize := len(ones)
18+
zeroSize := len(zeros)
19+
20+
res := size
21+
22+
i, j := 0, 0
23+
for i < oneSize {
24+
for j < zeroSize && zeros[j] < ones[i] {
25+
j++
26+
}
27+
res = min(res, i+zeroSize-j)
28+
i++
29+
}
30+
31+
res = min(res, oneSize)
32+
33+
return res
34+
}
35+
36+
func min(a, b int) int {
37+
if a < b {
38+
return a
39+
}
40+
return b
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package problem0926
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
// tcs is testcase slice
10+
var tcs = []struct {
11+
S string
12+
ans int
13+
}{
14+
15+
{
16+
"01000011110",
17+
2,
18+
},
19+
20+
{
21+
"00110",
22+
1,
23+
},
24+
25+
{
26+
"00110",
27+
1,
28+
},
29+
30+
{
31+
"010110",
32+
2,
33+
},
34+
35+
{
36+
"00011000",
37+
2,
38+
},
39+
40+
// 可以有多个 testcase
41+
}
42+
43+
func Test_minFlipsMonoIncr(t *testing.T) {
44+
ast := assert.New(t)
45+
46+
for _, tc := range tcs {
47+
ast.Equal(tc.ans, minFlipsMonoIncr(tc.S), "输入:%v", tc)
48+
}
49+
}
50+
51+
func Benchmark_minFlipsMonoIncr(b *testing.B) {
52+
for i := 0; i < b.N; i++ {
53+
for _, tc := range tcs {
54+
minFlipsMonoIncr(tc.S)
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)