Leetcode # 2182. Construct String With Repeat Limit
Problem
https://leetcode.com/problems/construct-string-with-repeat-limit
Solution
Time Complexity: O(len(s))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: counter = Counter(s) chars = sorted(counter.keys(), reverse=True) print(counter, chars) rls = "" for i, ci in enumerate(chars): while counter[ci] > 0: n = min(counter[ci], repeatLimit) rls += ci * n counter[ci] -= n if counter[ci] == 0: break rls_changed = False for j, cj in enumerate(chars[i + 1:]): if counter[cj] == 0: continue rls += cj counter[cj] -= 1 rls_changed = True break if not rls_changed: break return rls
Last Updated on 2024/12/17 by A1go