項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Leetcode】python – [2264] Largest 3-Same-Digit Number in String 個人解法筆記 | 292nd LeetCode Weekly Contest

題目出處

2264. Largest 3-Same-Digit Number in String

難度

easy

個人範例程式碼

class Solution:
    def largestGoodInteger(self, num: str) -> str:
        if not num or len(num) <= 2:
            return ""

        ans = -1
        for i, c in enumerate(num):
            if i <= len(num)-3 and num[i] == num[i+1] and num[i] == num[i+2]: # 012, 3 - 3 = 0
                ans = max(int(num[i:i+3]), ans)

        if ans == -1:
            return ""
        if ans == 0:
            return "000"
        return str(ans)

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

這題就是要找連續三個數字,然後要最大,
簡單的字串處理,稍微小心細節處理即可。

我們用 int 紀錄文字,初始 -1

  • 如果最後沒找到 (-1),就回傳 “”
  • 最後得到 0,回傳 “000” (轉 int 會消失)
  • 其他回傳 str(對應數字)

input handling

如果 no input 或 input len <= 2,為不可能的 case,return “”

Boundary conditions

用 for 控制範圍

Reference

⭐ Leetcode 解題紀錄 ⭐題型資料結構Python SolutionC++ SolutionNote
⭐BFS 相關題型 ⭐
104Maximum Depth of Binary TreeBFS (分層)Python
94Binary Tree Inorder TraversalBFS (分層)TreePython 內含 處理 Tree 樹問題的重點
102Binary Tree Level Order TraversalBFS (分層)TreePython
103Binary Tree Zigzag Level Order TraversalBFS (分層)TreePython
107Binary Tree Level Order Traversal IIBFS (分層)TreePython
133Clone GraphBFS (分層)GraphPython Graph 的基本操作 #重要題型
127Word LadderBFS (分層), DFSGraphPython
[Lint] 127Topological SortingBFS (拓撲)Python
內有 indegree, outdegree 介紹 #重要題型
207Course ScheduleBFS (拓樸)GraphPython
210Course Schedule IIBFS (拓樸)GraphPython
[Lint] 892Alien DictionaryBFS (拓樸)GraphPython
[Lint] 431Connected Component in Undirected GraphBFS (連通塊)GraphPython 內含 BFS 模板 #重要題型
1091Shortest Path in Binary MatrixBFS (最短路徑)MatrixPython
⭐ Binary Serach 相關題型 ⭐
33Search in Rotated Sorted ArrayBinary SerachArrayPython #重要題型
34Find First and Last Position of Element in Sorted ArrayBinary SerachPython
50Pow(x, n) Binary Serach