Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告
2017-01-17 14:11
453 查看
1 解题思想
题目要求给一个字符串,要求将字符串中的字符,按照字符出现的频率进行排序,从大到小的输出(某个字符出现了多少就输出多少次,只是重组)解题方法:
1、统计
2、使用TreeMap,将相同频率的字符存在一起,然后按照key=频率的方式放入TreeMap
3、遍历TreeMap输出
2 原题
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "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: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "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.
3 AC解
public class Solution { public String frequencySort(String s) { int frequency[] = new int[256]; for(char c:s.toCharArray()){ frequency[c] ++; } // 统计频率,使用Treemap排序,这里白板写的代码,直接将频率取反,这样方便 TreeMap<Integer,String> map= new TreeMap<Integer,String>(); for(int i=0;i<256;i++){ if(frequency[i] == 0) continue; StringBuilder sb = new StringBuilder(map.getOrDefault(-frequency[i],"")); for(int j=0;j<frequency[i];j++) sb.append((char)i); map.put(-frequency[i],sb.toString()); } StringBuilder sb = new StringBuilder(); Iterator it = map.keySet().iterator(); while(it.hasNext()){ Integer key = (Integer)it.next(); sb.append(map.get(key)); } return sb.toString(); } }
相关文章推荐
- Leetcode 97. Interleaving String 交错字符判别 解题报告
- Leetcode451. 对字符出现频率进行排序
- Leetcode 127. Word Ladder 字符变换 解题报告
- [LeetCode] Sort Characters By Frequency 根据字符出现频率排序
- [LeetCode] 451. Sort Characters By Frequency 根据字符出现频率排序
- Leetcode 87. Scramble String 字符交换 解题报告
- Leetcode 451. Sort Characters By Frequency 按频率对字符排序
- LeetCode 451. Sort Characters By Frequency (根据字符出现频率排序)
- Leetcode 126. Word Ladder II 字符变换2 解题报告
- Leetcode 387. First Unique Character in a String 第一个唯一字符 解题报告
- Leetcode 75. Sort Colors 色彩排序 解题报告
- [LeetCode] Interleaving String 解题报告
- [LeetCode] Implement strStr() 解题报告
- [LeetCode] Largest Rectangle in Histogram 解题报告
- [LeetCode] Jump Game 解题报告
- [LeetCode] Edit Distance 解题报告
- [LeetCode] Longest Palindromic Substring 解题报告
- [LeetCode] Generate Parentheses 解题报告
- [LeetCode] Flatten Binary Tree to Linked List 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告