LeetCode 筆記 - 1446. Consecutive Characters

題目在此 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

也許你也會想看看