Notice
Recent Posts
Recent Comments
Link
.Zzumbong
[leetCode/JS] 451. Sort Characters By Frequency ๋ณธ๋ฌธ
๋์ด๋ [ ๐ค ] Medium
๋ฌธ์ ์ค๋ช
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.
๋ฌธ์์ด s์ ๋ฌธ์๊ฐ ๋ฑ์ฅํ์๋งํผ ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌํ๋ค.
aaaccc, cccaaa ๋ ๋๋ค ์ ๋ต์ด๋๋ค. ์ซ์๋ง ์ ๊ฒฝ์ฐ๋ฉด ๋๋ค.
์ ์ถ๋ ฅ ์
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.
๋ด ์๋ฃจ์
- ๋ฌธ์์ด์
hasmap
์ผ๋ก ๋ฌธ์๋ฅผkey
๋ก, ๋ฑ์ฅ ์ซ์๋ฅผvalue
๋ก ๋ง๋ ํ - ์ค๋ฆ์ฐจ์์ผ๋ก
sorting
ํ๋ค. map
์ผ๋กrepeat
ํ์ฌ ๋ฐ๋ณต์ํจ ํ ๋ฐฐ์ด์join
ํด์ ๋ฌธ์์ด๋ก ๋ฆฌํดํ๋ค.
/**
* @param {string} s
* @return {string}
*/
var frequencySort = function(s) {
// s = tree
const map = {}
for(const str of s) {
map[str] = (map[str] || 0) + 1;
}
// map: { t: 1, r: 1, e: 2 }
return Object.entries(map)
.sort((a, b) => b[1] - a[1]) // [ [ 'e', 2 ], [ 't', 1 ], [ 'r', 1 ] ]
.map(s => s[0].repeat(s[1])) // [e, e, r, t]
.join(''); // 'eert'
};
๊ฐ์ํ
- ์๊ฐ๋ณด๋ค ๊น๋ค๋ก์ ๋ค.
- reduce๋ฅผ ์ธ์ง ๊ทธ๋ฅ for ๋ฌธ์ผ๋ก ๋๋ฆด์ง ์กฐ๊ธ ๋๋ฆฌ๋๋ผ๋ ์ด์๊ฒ ๋ง๋ค์ง?
- ๊ณ ๋ฏผํ๋ ์๊ฐ์ด ์ข๊ฑธ๋ ธ๋ค. repeat์ ์๊ฐํ์ง ๋ชปํ๋ค๋ฉด ์กฐ๊ธ ๋๋ฌ์ด ์ฝ๋๊ฐ ๋์ ๊ฐ๋ฅ์ฑ์ด ํฌ๋ค.
- ๊ทธ๋ฆฌ๊ณ ์์ด๋ ๊ฒ ๋น ๋ฅด์ง?
'coding test > leetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetCode/JS] 876. Middle of the Linked List (0) | 2022.12.05 |
---|---|
[leetCode/JS] 2256. Minimum Average Difference (0) | 2022.12.04 |
[leetCode/JS] 1657. Determine if Two Strings Are Close (0) | 2022.12.02 |
[leetCode/JS] 1704. Determine if String Halves Are Alike (0) | 2022.12.01 |
[leetCode/JS] 1207. Unique Number of Occurrences (0) | 2022.11.30 |
0 Comments