Arrangement
Last updated
Last updated
class Solution:
def rearrangeString(self, s: str, k: int) -> str:
if k == 0:
return s
# calculate histogram counter
charToFreq = collections.Counter(s)
maxHeap = []
for key, value in charToFreq.items():
heapq.heappush(maxHeap, (-value, key))
# take items from maxHeap and append them behind result
result = ""
while len(maxHeap) > 0:
if len(maxHeap) < k:
negFreq, char = heapq.heappop(maxHeap)
if abs(negFreq) > 1:
break
heapq.heappush(maxHeap, (negFreq, char))
roundLength = min(k, len(maxHeap))
queue = []
for i in range(roundLength):
negFreq, char = heapq.heappop(maxHeap)
result += char
if negFreq + 1 != 0:
queue.append((negFreq + 1, char))
while queue:
heapq.heappush(maxHeap, queue.pop())
return resultclass Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
# calculate histogram
histogram = collections.Counter(tasks)
maxHeap = []
for key, value in histogram.items():
heapq.heappush(maxHeap, (-value, key))
n += 1
# repeat the loop until maxHeap becomes empty
result = 0
while maxHeap:
thisRound = 0
fromHeap = min(len(maxHeap), n)
# for each round take first n items from heap
# decrement and put back
queue = []
result += fromHeap
for i in range(fromHeap):
negValue, key = heapq.heappop(maxHeap)
if negValue + 1 != 0:
queue.append((negValue + 1, key))
for item in queue:
heapq.heappush(maxHeap, item)
if fromHeap < n and len(maxHeap) > 0:
# when the heap size is smaller than n, use idle to pad
result += n - fromHeap
return resultclass Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
big, bigNum = "a", a
small, smallNum = "b", b
if bigNum < smallNum:
bigNum, smallNum = smallNum, bigNum
big, small = small, big
result = ""
# first stage, construct aab, if b > 0
diff = bigNum - smallNum
result = result + min(diff, smallNum) * (big + big + small) # need to prove two big exist
bigNum -= 2 * min(diff, smallNum)
smallNum -= min(diff, smallNum)
# second stage, construct ab if num(b) > 0
if smallNum > 0:
result = result + smallNum * (big + small)
bigNum -= smallNum
# third stage, construct remaining a
if bigNum > 0:
result = result + bigNum * big
return result