LeetCode 筆記 - 1446. Consecutive Characters

LeetCode 第 1446 題解析,尋找字串中最長的連續單一字元長度。本文採取直覺的線性掃描策略,透過一次遍歷並動態比對前後字元,精確掌握連續區段的最大值。這是一篇鍛鍊基礎字串處理與計數邏輯的入門練習。

發佈
閱讀
約 1 分鐘
字數
153

題目在此 1446. Consecutive Characters

給定一個字串,請問連續字串中最長的連續字元長度?

解題思維

每個字元掃過一次,如果跟開始字元相同,則長度加一,否則就計算長度看看有沒有比看過的長度更長。

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def maxPower(self, s: str) -> int:

if (size := len(s)) == 1:
return 1

result = 0
pre_index = 0
for i in range(size):
if s[i] != s[pre_index]:
result = max(result, i - pre_index)
pre_index = i

result = max(result, i - pre_index + 1)

return result
image 106

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟