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

LeetCode 3798: Largest Even Number

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

基本資料
#

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

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

解題思路
#

字串只有 1 和 2,偶數只要最後一位是 2。位數越多數字越大,所以只刪必要的:把結尾連續的 1 刪掉,剩下的就是最大的偶數。全部都是 1 就是空字串。

我的解法
#

class Solution:
    def largestEven(self, s: str) -> str:
        return s.rstrip("1")

我當時用 while 迴圈一個一個刪,rstrip 是同一件事。

複雜度
#

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

要特別避免的錯誤
#

  • 刪中間的字只會讓數字變短變小,只需要處理結尾。

面試口說整理
#

偶數只看最後一位,而保留越多位數越大,所以我只把結尾的 1 刪掉。時間 O(n)。

相關文章

LeetCode 2269: Find the K-Beauty of a Number
·1 分鐘
LeetCode Easy Sliding-Window Math String
LeetCode 2269 解題筆記:把數字轉成字串,枚舉每個長度 k 的子字串;0 不能當除數
LeetCode 3794: Reverse String Prefix
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 3794 解題筆記:切片一行解決;手寫雙指針時要先把字串轉成 list
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·1 分鐘
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 解題筆記:把二進位字串跟它的反轉逐位比較,不同的位數就是答案
LeetCode 2264: Largest 3-Same-Digit Number in String
·1 分鐘
LeetCode Easy String
LeetCode 2264 解題筆記:候選只有 “000” 到 “999” 十個,從 “999” 往下檢查有沒有在字串裡
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