[Swift]LeetCode926. 將字串翻轉到單調遞增 | Flip String to Monotone Increasing
阿新 • • 發佈:2018-11-07
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'
'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'
組成的字串,是以一些 '0'
(可能沒有 '0'
)後面跟著一些 '1'
(也可能沒有 '1'
)的形式組成的,那麼該字串是單調遞增
我們給出一個由字元 '0'
和 '1'
組成的字串 S
,我們可以將任何 '0'
翻轉為 '1'
或者將 '1'
翻轉為 '0'
。
返回使 S
單調遞增的最小翻轉次數。
示例 1:
輸入:"00110" 輸出:1 解釋:我們翻轉最後一位得到 00111.
示例 2:
輸入:"010110" 輸出:2 解釋:我們翻轉得到 011111,或者是 000111。
示例 3:
輸入:"00011000" 輸出:2 解釋:我們翻轉得到 00000000。
提示:
1 <= S.length <= 20000
S
中只包含字元'0'
和'1'
116ms
1 class Solution { 2 func minFlipsMonoIncr(_ S: String) -> Int { 3 var arr:[Character] = [Character]() 4 for char in S.characters 5 { 6 arr.append(char) 7 } 8 let len = S.count 9 //宣告陣列 10 var ct:[Int] = [Int](repeating: 0,count: len + 1) 11 var x:Int = 0 12 for i in 0...len 13 { 14 ct[i] += x 15 if i < len && arr[i] == "1" 16 { 17 x += 1 18 } 19 } 20 x = 0 21 for i in (0...len).reversed() 22 { 23 ct[i] += x 24 if i > 0 && arr[i - 1] == "0" 25 { 26 x += 1 27 } 28 } 29 var res = 999999999 30 for i in 0...len 31 { 32 res = min(res,ct[i]) 33 } 34 return res 35 } 36 }