알고리즘 문제/Leetcode

451. Sort Characters By Frequency

BEstyle 2023. 2. 5. 18:12

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

 

Example 1:

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

 

Constraints:

  • 1 <= s.length <= 5 * 105
  • s consists of uppercase and lowercase English letters and digits.

# https://leetcode.com/problems/sort-characters-by-frequency/

'''
1. 아이디어 :
    1)  Counter를 사용하여 문자열의 각 문자의 빈도수를 구한다.
        Counter를 배열로 반환하고 정렬한다.
        배열의 각 element안에 빈도수 만큼 ans에 추가한다.
2. 시간복잡도 :
    1)  O(n) + O(nlogn) + O(n) = O(nlogn)
    -   Counter를 사용하여 문자열의 각 문자의 빈도수를 구하는 시간 + 정렬 시간 + 정답 String 만드는 시간
3. 자료구조 :
    1) 해시
'''

from collections import Counter
class Solution:
    def frequencySort(self, s: str) -> str:
        c = Counter(s)
        print(c)

        temp=[]
        for key,val in hash.items():
            temp.append([key,val])

        temp.sort(key = lambda x : x[1], reverse=True)
        print(temp)

        ans = ""
        for chars in temp:
            for i in range(chars[1]):
                ans+=chars[0]
        return ans