926. Flip String to Monotone Increasing(python+cpp)
阿新 • • 發佈:2018-11-13
題目:
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.)
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'
.
Return the minimum number of flips to make S monotone increasing.
Example 1:Input: "00110" Output: 1 Explanation: We flip the last digit to get 00111.
Example 2:
Input: "010110" Output: 2 Explanation: We flip to get 011111, or alternatively 000111.
Example 3:
Input: "00011000" Output: 2 Explanation: We flip to get 00000000.
Note:
1 <= S.length <= 20000
S
only consists of'0'
and'1'
characters.
解釋:
可以是把0
翻轉成1
,也可以是把1
翻轉成0
。
其實是個動態規劃問題。
詳細說明:
1.當遍歷到'1'
時, 不需要翻轉,因為'1'
本身就應該在字串的尾巴處
2.當遍歷到'0'
時,我們有兩種選擇:
a.在原字串經過flipCount翻轉之後,把新加入的 '0'
flip為'1'
,所以需要flipCount++
b.不翻轉此處的'0'
,那麼它前面的'1'
都需要變成'0'
,它前面的'1'
的個數是oneCount,所以需要翻轉原字串中的oneCount個'1'
為'0'
(也就是說,如果決定了遇到'1'
不進行翻轉,那麼前面無論怎麼翻轉的都不管了,只需要把前面的所有的'1'
'0'
即可)。 因此 ,動態規劃在’0‘
的情況下結果是min(flipCount + 1, oneCount)
這個結果就是新的flipCount
pythond程式碼:
class Solution:
def minFlipsMonoIncr(self, S):
"""
:type S: str
:rtype: int
"""
oneCount=0
flipCount=0
for letter in S:
if letter=='1':
oneCount+=1
#遇到0的情況,要麼翻轉這個0,flipCount++,要麼翻轉之前所有的1
else:
flipCount=min(flipCount+1,oneCount)
return flipCount
c++程式碼:
class Solution {
public:
int minFlipsMonoIncr(string S) {
int flipCount=0,oneCount=0;
for(auto letter:S)
{
if (letter=='1')
oneCount++;
else
flipCount=min(flipCount+1,oneCount);
}
return flipCount;
}
};
總結: