【哈希表】LeetCode 767. 重构字符串
题目链接
思路
先用哈希表统计出出现次数最多的字符,如果这个次数大于一半,说明这个字符总会挨在一起,直接返回 ""
。
如果不超过一半,则先把字符填在偶数位置(先填出现次数最多的字符),偶数位置填满了再填奇数位置。
代码
class Solution {
public String reorganizeString(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
int threshold = (n + 1) / 2;
HashMap<Character, Integer> hashMap = new HashMap<>();
for(char c : chars){
hashMap.put(c, hashMap.getOrDefault(c, 0) + 1);
}
ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<>(hashMap.entrySet());
Collections.sort(list, (a, b) -> (b.getValue() - a.getValue()));
if(list.get(0).getValue() > threshold){
return "";
}
char[] result = new char[n];
Map.Entry<Character, Integer> temp = list.get(0);
int index = 0;
for(; index < n && temp.getValue() > 0; index += 2){
result[index] = temp.getKey();
temp.setValue(temp.getValue() - 1);
}
// 这里不重置 index,因为偶数位可能还没有被填完,所以需要接着填偶数位
for(int j = 1; j < list.size(); j++){
temp = list.get(j);
while(temp.getValue() > 0){
temp.setValue(temp.getValue() - 1);
// 偶数位填完了,开始填奇数位
if(index >= n){
index = 1;
}
result[index] = temp.getKey();
index += 2;
}
}
return new String(result);
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)