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

LeetCode 2745: Construct the Longest New String

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

基本資料
#

難易度: medium 第一次嘗試:2025-07-22

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

解題思路
#

不能出現 AAA 或 BBB:

  • AA 後面不能接 AA 或 AB(會變成 AAA),只能接 BB。
  • BB 後面不能接 BB,可以接 AA 或 AB。
  • AB 後面可以接 AA 或 AB,不能接 BB。

所以 AA 和 BB 一定要交替:AABBAABB...,最多用 min(x, y) 對;如果有一種比較多,可以在頭或尾再多放一個。AB 全部可以串在一起,接在 BB 後面、AA 前面(...BB ABAB AA...),所以全部都用得上。

x == y:(2x + z) × 2
x != y:(2 × min(x, y) + 1 + z) × 2

我的解法
#

class Solution:
    def longestString(self, x: int, y: int, z: int) -> int:
        pairs = min(x, y)
        pieces = 2 * pairs + (1 if x != y else 0) + z     # 用了幾個字串
        return pieces * 2                                 # 每個字串長度 2

LeetCode 的標籤是 DP(可以用 dp[x][y][z][上一個是什麼] 做),但找出規律之後是 O(1)。

複雜度
#

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

要特別避免的錯誤
#

  • 以為 AB 有限制:ABAB 不會產生 AAA 或 BBB,全部都能用。

面試口說整理
#

AA 後面只能接 BB,所以 AA 和 BB 一定交替,最多用比較少的那種的兩倍,多的那種再多一個;AB 可以全部串在一起,放在 BB 和 AA 之間。算出用了幾個字串再乘 2。時間 O(1)。

相關文章

LeetCode 313: Super Ugly Number
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 313 解題筆記:LC 264 的推廣,每個質數一個指針;用 heap 的話要避免同一個數被推進去很多次
LeetCode 396: Rotate Function
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 396 解題筆記:F(k) 和 F(k - 1) 只差一個公式:F(k) = F(k - 1) + sum - n × 被移到最前面的那個數
LeetCode 397: Integer Replacement
·1 分鐘
LeetCode Medium Dynamic-Programming Greedy Bit-Manipulation Memoization
LeetCode 397 解題筆記:偶數一定除以 2;奇數選 +1 或 -1,用記憶化遞迴;n 很大不能開 n 大小的陣列
LeetCode 435: Non-overlapping Intervals
·1 分鐘
LeetCode Medium Array Dynamic-Programming Greedy Sorting
LeetCode 435 解題筆記:最少刪幾個 = 總數減掉最多能保留幾個;按右端點排序,貪心保留結束最早的
LeetCode 264: Ugly Number II
·1 分鐘
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
LeetCode 264 解題筆記:三個指針分別指向下一個要乘 2、3、5 的醜數,每次取最小的,相等的指針都要前進
LeetCode 1025: Divisor Game
·1 分鐘
LeetCode Easy Math Dynamic-Programming Brainteaser Game-Theory
LeetCode 1025 解題筆記:dp[i] = 存在 i 的因數 x 讓 dp[i - x] 是輸;觀察後答案就是 n 是偶數