Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ac4e94b

Browse files
author
weiy
committed
flip string to monotone increasing medium
1 parent a1a08ad commit ac4e94b

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

‎DP/FlipStringToMonotoneIncreasing.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""
2+
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.)
3+
4+
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'.
5+
6+
Return the minimum number of flips to make S monotone increasing.
7+
8+
9+
10+
Example 1:
11+
12+
Input: "00110"
13+
Output: 1
14+
Explanation: We flip the last digit to get 00111.
15+
Example 2:
16+
17+
Input: "010110"
18+
Output: 2
19+
Explanation: We flip to get 011111, or alternatively 000111.
20+
Example 3:
21+
22+
Input: "00011000"
23+
Output: 2
24+
Explanation: We flip to get 00000000.
25+
26+
27+
Note:
28+
29+
1 <= S.length <= 20000
30+
S only consists of '0' and '1' characters.
31+
32+
33+
给定一个由 '0' 和 '1' 组成的字符串,把它变成单调递增的字符串。返回最少的改变次数。
34+
35+
思路:
36+
从左向右走过一遍,把找到的 1 变成 0。
37+
从右向左过一遍,把找到的 0 变成 1。
38+
39+
最后过一遍,找到相加最少的一个点即可(可能不止一个)。
40+
41+
测试地址:
42+
https://leetcode.com/contest/weekly-contest-107/problems/flip-string-to-monotone-increasing/
43+
44+
"""
45+
46+
class Solution(object):
47+
def minFlipsMonoIncr(self, S):
48+
"""
49+
:type S: str
50+
:rtype: int
51+
"""
52+
53+
x = [0] if S[0] == '0' else [1]
54+
55+
# left to right
56+
# 1 -> 0
57+
for i in range(1, len(S)):
58+
if S[i] == '1':
59+
x.append(x[-1]+1)
60+
else:
61+
x.append(x[-1])
62+
63+
# right to left
64+
# 0 -> 1
65+
S = S[::-1]
66+
y = [0] if S[0] == '1' else [1]
67+
for i in range(1, len(S)):
68+
if S[i] == '0':
69+
y.append(y[-1]+1)
70+
else:
71+
y.append(y[-1])
72+
73+
y.reverse()
74+
75+
return min([i+j for i,j in zip(x,y)]) - 1
76+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /