【哈希表】LeetCode 767. 重构字符串

题目链接

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);
    }
}
posted @ 2023-04-26 16:46  Frodo1124  阅读(15)  评论(0编辑  收藏  举报