↓快轉到主要內容
  1. LeetCode/

LeetCode 3800: Minimum Cost to Make Two Binary Strings Equal

·1 分鐘· ·
LeetCode Medium Greedy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-01-04

  • 提交紀錄:Accepted(一次通過)

解題思路
#

只有 s[i] != t[i] 的位置要處理,分成兩類:

  • c0:s[i] = 0, t[i] = 1。
  • c1:s[i] = 1, t[i] = 0。

修法(Greedy 模板四「配對與奇偶」):

情況做法成本
一個 c0 配一個 c1在 s 裡把這兩格交換min(swap, 2 × flip)
兩個同類先 cross 其中一格,它就變成另一類,再 swapmin(cross + swap, 2 × flip)
剩一個只能 flipflip

不同類的配對越多越好(min(c0, c1) 對),剩下的 |c0 - c1| 個同類兩兩配,奇數個時剩一個 flip。

我的解法
#

我當時列了三種整體方案取最小:全部 flip;不同類 swap、其餘 flip;不同類 swap、同類 cross + swap、剩一個 flip。這裡整理成每一種配對各自取最便宜:

class Solution:
    def minimumCost(self, s: str, t: str, flipCost: int, swapCost: int, crossCost: int) -> int:
        c = [0, 0]
        for a, b in zip(s, t):
            if a != b:
                c[int(a)] += 1
        pairs = min(c)                 # 不同類配對
        rest = abs(c[0] - c[1])        # 剩下的都是同一類
        return (pairs * min(swapCost, 2 * flipCost)
                + rest // 2 * min(crossCost + swapCost, 2 * flipCost)
                + rest % 2 * flipCost)

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 同類的兩格不能直接 swap(交換兩個一樣的值沒用),要先 cross 變成不同類。
  • 每一種配對都要跟「兩次 flip」比較,flip 可能比較便宜。

面試口說整理
#

我把不相等的位置分成 s 是 0 和 s 是 1 兩類。不同類的兩格用一次 swap 修好,同類的兩格先 cross 一格再 swap,剩一個只能 flip;每種都跟兩次 flip 比較取便宜的。時間 O(n)。

相關文章

LeetCode 2131: Longest Palindrome by Concatenating Two Letter Words
·1 分鐘
LeetCode Medium Greedy Hash-Table String Counting
LeetCode 2131 解題筆記:每個字跟它的反轉配成一對放兩邊;本身是回文的字也能兩兩配對,只有剩下的一個能放正中間
LeetCode 402: Remove K Digits
·1 分鐘
LeetCode Medium String Stack Greedy Monotonic-Stack
LeetCode 402 解題筆記:單調遞增 stack,遇到比頂端小的數字就把頂端刪掉(還有 k 次可刪時),最後去掉前導零
LeetCode 3799: Word Squares II
·1 分鐘
LeetCode Medium Backtracking Enumeration String
LeetCode 3799 解題筆記:四層枚舉,每一層先用角落字母剪枝,排序後輸出自然就是字典序
LeetCode 1016: Binary String With Substrings Representing 1 To N
·2 分鐘
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 解題筆記:s 最多 1000 個字元,長度固定時的子字串數量有限,n 太大一定是 False;從 n 往下檢查會很快失敗,或從每個起點往右最多延伸 30 位收集所有 <= n 的值
LeetCode 1888: Minimum Number of Flips to Make the Binary String Alternating
·1 分鐘
LeetCode Medium Sliding-Window String Dynamic-Programming
LeetCode 1888 解題筆記:把移到尾巴的操作變成在 s + s 上滑動長度 n 的視窗;視窗跟 0101… 不同的數量是 diff,跟 1010… 不同的就是 n - diff
LeetCode 3796: Find Maximum Value in a Constrained Sequence
·1 分鐘
LeetCode Medium Greedy Array
LeetCode 3796 解題筆記:每個位置的上界是自己的限制、左邊上界 + 差值、右邊上界 + 差值三者取最小;左右各掃一次