題目出處
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 Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 | Shortest Path in Binary Matrix | BFS (最短路徑) | Matrix | Python | ||
⭐ Binary Serach 相關題型 ⭐ | ||||||
33 | Search in Rotated Sorted Array | Binary Serach | Array | Python | #重要題型 | |
34 | Find First and Last Position of Element in Sorted Array | Binary Serach | Python | |||
50 | Pow(x, n) | Binary Serach |