JavaScript刷LeetCode -- 926. Flip String to Monotone Increasing
阿新 • • 發佈:2018-12-23
一、題目
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.
二、題目大意
一個由‘0’和‘1’組成的字串,可以通過將‘0’替換成‘1’,或者將‘1’替換成‘0’,使得整個字串單調遞增的最小操作次數是多少?
三、解題思路
因為字串中只含有0和1兩種元素,所以構成字串單調遞增的情況為:左邊為0右邊為1。
l[i]: 表示 1 到 i 全部為0需要的運算元
r[i]: 表示 max - i 到 max 全部為1需要的運算元
那麼形成一個單調遞增所需要的運算元為: l[i] + r[max - i]
只要比較所有的結果即可得到最小運算元。
四、程式碼實現
const minFlipsMonoIncr = (S) => { const max = S.length if (max <= 1) { return 0 } // l[i] 表示 0 ~ i 為0的情況 let l = [] l[0] = 0 // 左邊沒有0 for (let i = 1; i <= max; i++) { const item = S[i - 1] // 注意下標 l[i] = l[i - 1] + (item === '1' ? 1 : 0) } // r[i] 表示後 max - 1 - i ~ max - 1 為1的情況 let r = [] r[0] = 0 // 右邊沒有1 for (let i = 1; i <= max; i++) { const item = S[max - i] // 注意下標 r[i] = r[i - 1] + (item === '1' ? 0 : 1) } let min = Number.MAX_SAFE_INTEGER for (let i = 0; i <= max ; i++) { const lItem = l[i] const rItem = r[max - i] min = Math.min(rItem + lItem, min) } return min }
如果本文對您有幫助,歡迎關注我的微信公眾號【超愛敲程式碼】,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。