일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- Class
- concurrency
- Substring with Concatenation of All Words
- kaggle
- 컴퓨터의 구조
- Regular Expression
- Decorator
- iterator
- Python
- 시바견
- 43. Multiply Strings
- DWG
- 운영체제
- attribute
- Generator
- shiba
- data science
- 109. Convert Sorted List to Binary Search Tree
- LeetCode
- Python Implementation
- Python Code
- 밴픽
- Protocol
- t1
- 315. Count of Smaller Numbers After Self
- 30. Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- 파이썬
- 715. Range Module
- 프로그래머스
Archives
- Today
- Total
Scribbling
LeetCode: 358. Rearrange String k Distance Apart 본문
Computer Science/Algorithms & Data Structures
LeetCode: 358. Rearrange String k Distance Apart
focalpoint 2023. 3. 10. 23:01
Greedy solution with heap & deque
- append character with 'max frequency' currently
- put the appended character to a deque for cool-down
from collections import Counter, deque
import heapq
class Solution:
def rearrangeString(self, s: str, k: int) -> str:
if k <= 1:
return s
c = Counter(s)
h = [(-freq, char) for char, freq in c.items()]
heapq.heapify(h)
q = deque()
ret = []
while h:
freq, char = heapq.heappop(h)
freq *= -1
ret.append(char)
q.append((freq-1, char))
if len(q) >= k:
freq, char = q.popleft()
if freq >= 1:
heapq.heappush(h, (-freq, char))
return ''.join(ret) if len(ret) == len(s) else ""