牛客_重排字符串

重排字符串
https://www.nowcoder.com/practice/6c3a5604cf274b2287fbe27c5dc74743

import java.util.*;

/**
 * NC379 重排字符串
 * @author d3y1
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @return string字符串
     */
    public String rearrangestring (String str) {
        int len = str.length();
        int[] charCount = new int[26];
        PriorityQueue<Letter> maxHeap = new PriorityQueue<>((o1, o2)->(o2.count-o1.count));
        
        // 统计字符次数
        for(int i=0; i<len; i++){
            charCount[str.charAt(i)-'a']++;
        }

        // build maxHeap
        for(int i=0; i<26; i++){
            if(charCount[i] > 0){
                maxHeap.add(new Letter((char)('a'+i), charCount[i]));
            }
        }

        // 贪心: 最多字符+次多字符
        StringBuilder sb = new StringBuilder();
        Letter first,second;
        while(maxHeap.size() >= 2){
            first = maxHeap.poll();
            second = maxHeap.poll();
            sb.append(first.ch);
            sb.append(second.ch);
            if(first.count > 1){
                first.count--;
                maxHeap.add(first);
            }
            if(second.count > 1){
                second.count--;
                maxHeap.add(second);
            }
        }

        if(!maxHeap.isEmpty()){
            first = maxHeap.poll();
            if(first.count > 1){
                return "";
            }else{
                sb.append(first.ch);
            }
        }

        return sb.toString();
    }

    /**
     * 英文字母
     */
    private class Letter {
        char ch;
        int count;

        public Letter(char ch, int count){
            this.ch = ch;
            this.count = count;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值