451:根据字符出现频率排序

This commit is contained in:
huangge1199@hotmail.com 2021-07-03 23:47:33 +08:00
parent 00c8b3dbbe
commit dcf5b30433
4 changed files with 134 additions and 2 deletions

View File

@ -0,0 +1,88 @@
//给定一个字符串请将字符串里的字符按照出现的频率降序排列
//
// 示例 1:
//
//
//输入:
//"tree"
//
//输出:
//"eert"
//
//解释:
//'e'出现两次'r''t'都只出现一次
//因此'e'必须出现在'r''t'之前此外"eetr"也是一个有效的答案
//
//
// 示例 2:
//
//
//输入:
//"cccaaa"
//
//输出:
//"cccaaa"
//
//解释:
//'c''a'都出现三次此外"aaaccc"也是有效的答案
//注意"cacaca"是不正确的因为相同的字母必须放在一起
//
//
// 示例 3:
//
//
//输入:
//"Aabb"
//
//输出:
//"bbAa"
//
//解释:
//此外"bbaA"也是一个有效的答案"Aabb"是不正确的
//注意'A''a'被认为是两种不同的字符
//
// Related Topics 哈希表 字符串 桶排序 计数 排序 优先队列
// 👍 310 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
//451:根据字符出现频率排序
class SortCharactersByFrequency {
public static void main(String[] args) {
//测试代码
Solution solution = new SortCharactersByFrequency().new Solution();
System.out.println(solution.frequencySort("tree"));
System.out.println(solution.frequencySort("raaeaedere"));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap();
for (char ch : s.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
HashMap<Character, Integer> mapSort = new LinkedHashMap<>();
map.entrySet()
.stream()
.sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
.collect(Collectors.toList()).forEach(ele -> mapSort.put(ele.getKey(), ele.getValue()));
StringBuilder sBuilder = new StringBuilder();
for (char ch : mapSort.keySet()) {
for (int i = 0; i < mapSort.get(ch); i++) {
sBuilder.append(ch);
}
}
s = sBuilder.toString();
return s;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,44 @@
<p>给定一个字符串,请将字符串里的字符按照出现的频率降序排列。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
&quot;tree&quot;
<strong>输出:</strong>
&quot;eert&quot;
<strong>解释:
</strong>&#39;e&#39;出现两次,&#39;r&#39;&#39;t&#39;都只出现一次。
因此&#39;e&#39;必须出现在&#39;r&#39;&#39;t&#39;之前。此外,&quot;eetr&quot;也是一个有效的答案。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
&quot;cccaaa&quot;
<strong>输出:</strong>
&quot;cccaaa&quot;
<strong>解释:
</strong>&#39;c&#39;&#39;a&#39;都出现三次。此外,&quot;aaaccc&quot;也是有效的答案。
注意&quot;cacaca&quot;是不正确的,因为相同的字母必须放在一起。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>
&quot;Aabb&quot;
<strong>输出:</strong>
&quot;bbAa&quot;
<strong>解释:
</strong>此外,&quot;bbaA&quot;也是一个有效的答案,但&quot;Aabb&quot;是不正确的。
注意&#39;A&#39;&#39;a&#39;被认为是两种不同的字符。
</pre>
<div><div>Related Topics</div><div><li>哈希表</li><li>字符串</li><li>桶排序</li><li>计数</li><li>排序</li><li>堆(优先队列)</li></div></div>\n<div><li>👍 310</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long