From ff130cf84888c94a75375b91b031313af6af1e5c Mon Sep 17 00:00:00 2001 From: bumpsoo Date: Tue, 17 Dec 2024 22:35:13 +0900 Subject: [PATCH] https://leetcode.com/problems/construct-string-with-repeat-limit --- medium/construct_string_with_repeat_limit.py | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 medium/construct_string_with_repeat_limit.py diff --git a/medium/construct_string_with_repeat_limit.py b/medium/construct_string_with_repeat_limit.py new file mode 100644 index 0000000..70bf749 --- /dev/null +++ b/medium/construct_string_with_repeat_limit.py @@ -0,0 +1,31 @@ +# https://leetcode.com/problems/construct-string-with-repeat-limit + +class Solution: + def repeatLimitedString(self, s: str, repeatLimit: int) -> str: + cnt = {} + for ch in s: + if ch in cnt: + cnt[ch] += 1 + else: + cnt[ch] = 1 + result = [] + while len(cnt) > 0: + key = max(cnt) + count = cnt[key] + cnt.pop(key) + while count > repeatLimit: + count -= repeatLimit + for _ in range(repeatLimit): + result.append(key) + if len(cnt) == 0: + return ''.join(result) + sub_key = max(cnt) + result.append(sub_key) + cnt[sub_key] -= 1 + if cnt[sub_key] == 0: + cnt.pop(sub_key) + for _ in range(count): + result.append(key) + + return ''.join(result) +