classSolution1: defmaximumLength(self, s: str) -> int: n = len(s) # groups = [Counter() for _ in range(26)] # TLE groups = [[0] * (n + 1) for _ inrange(26)] # AC i = 0 while i < n: # 分組循環 st, i, idx = i, i + 1, ord(s[i]) - ord("a") while i < n and s[i] == s[st]: i += 1 # for k in range(1, i - st + 1): # 長度為 k 的子字串有 i - st - k + 1 個 for k inrange(i - st, max(0, i - st - 3), -1): # 其實最多考慮 3 個就夠了 groups[idx][k] += i - st - k + 1 ans = -1 for g in groups: # for i in range(n, 0, -1): for i inrange(n - 2, 0, -1): # 需要出現至少 3 次 if g[i] >= 3: # 滿足條件 ans = max(ans, i) break return ans
classSolution2: defmaximumLength(self, s: str) -> int: n = len(s) groups = [[] for _ inrange(26)] i = 0 while i < n: # 分組循環 st, i = i, i + 1 while i < n and s[i] == s[st]: i += 1 groups[ord(s[st]) - ord("a")].append(i - st) ans = 0 for g in groups: m = len(g) if m == 0: continue g.sort(reverse=True) ans = max(ans, g[0] - 2) if m > 1: ans = max(ans, min(g[0] - 1, g[1])) if m > 2: ans = max(ans, g[2]) return ans if ans > 0else -1
classSolution3: defmaximumLength(self, s: str) -> int: n = len(s) groups = [[] for _ inrange(26)] i = 0 while i < n: # 分組循環 st = i while i < n and s[i] == s[st]: i += 1 idx = ord(s[st]) - ord("a") iflen(groups[idx]) >= 3: heappushpop(groups[idx], (i - st)) # Min heap else: heappush(groups[idx], (i - st)) # Min heap ans = 0 for g in groups: m = len(g) if m == 0: continue # top = [0] * 3 # for i in range(m - 1, -1, -1): # top[i] = heappop(g) top = sorted(g + [0] * (3 - m), reverse=True) ans = max(ans, top[0] - 2, min(top[0] - 1, top[1]), top[2]) return ans if ans > 0else -1
寫在最後
Cover Image Credit
The cover image was created by @月影暗霜. All rights belong to the original artist.
If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.