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

LeetCode 2264: Largest 3-Same-Digit Number in String

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

基本資料
#

難易度: easy 第一次嘗試:2025-08-14

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

解題思路
#

好的整數一定是 "ddd" 的形式,只有 10 種。從最大的 "999" 往下,第一個出現在 num 裡的就是答案(String 模板三)。

我的解法
#

我當時用長度 3 的滑動視窗加 Counter,視窗裡只有一種字元時跟目前答案比大小。枚舉 10 個候選更簡單:

class Solution:
    def largestGoodInteger(self, num: str) -> str:
        for d in "9876543210":
            if d * 3 in num:
                return d * 3
        return ""

複雜度
#

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

要特別避免的錯誤
#

  • 答案是字串,"000" 也是合法的答案,不能轉成整數。

面試口說整理
#

好的整數只有 "000" 到 "999" 十種,我從大到小檢查哪一個出現在字串裡,第一個找到的就是答案。時間 O(n)。

相關文章

LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪
LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 3541 解題筆記:數每個字元的次數,母音取最大、子音取最大再相加;沒有的那一類算 0
LeetCode 3606: Coupon Code Validator
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 3606 解題筆記:先過濾合法的優惠券,再用(類別順序, code)排序;字元範圍要包含 z、Z、9
LeetCode 1768: Merge Strings Alternately
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 1768 解題筆記:兩個指針輪流取字元,短的用完後接上長的剩下部分
LeetCode 2000: Reverse Prefix of Word
·1 分鐘
LeetCode Easy Two-Pointers String Stack
LeetCode 2000 解題筆記:找到 ch 第一次出現的位置 i,把 word[:i + 1] 反轉接上後面;找不到就原樣回傳
LeetCode 3120: Count the Number of Special Characters I
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 3120 解題筆記:分別收集出現過的小寫和大寫字母,兩個集合的交集大小就是答案