Tech for good

[Leetcode/Heap] 451. Sort Characters By Frequency 본문

IT/Computer Science

[Leetcode/Heap] 451. Sort Characters By Frequency

Diana Kang 2025. 4. 7. 22:53

class Solution:
    def frequencySort(self, s: str) -> str:
        # Step 1: Count frequency of each character
        freq = Counter(s)
        
        # Step 2: Build max-heap based on frequency
        # Use -count to simulate max-heap
        heap = [(-count, char) for char, count in freq.items()]
        heapq.heapify(heap)

        # Step 3: Build the result string from the heap
        result = []
        while heap:
            count, char = heapq.heappop(heap)
            result.append(char * (-count))  # Multiply char by its original count

        return ''.join(result)