题目来源:https://leetcode.com/problems/sort-characters-by-frequency
题目难度:Medium
解答1[Java]:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public String frequencySort(String s) { int[] map = new int[128]; for (char c : s.toCharArray()) { map[c]++; } char[] res = new char[s.length()]; int pos = 0; while (pos < s.length()) { char max = 0; for (char c = 0; c < map.length; c++) { if (map[c] > map[max]) max = c; } int repeat = map[max]; for (int i = 0; i < repeat; i++) { res[pos++] = max; map[max]--; } } return new String(res); } }
|