leetcode【每日一题】767. 重构字符串 java【今天起断更】

题干

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

若可行,输出任意可行的结果。若不可行,返回空字符串。

示例 1:

输入: S = "aab"
输出: "aba"
示例 2:

输入: S = "aaab"
输出: ""
注意:

S 只包含小写字母并且长度在[1, 500]区间内。

想法

由于考研 十二月的每日一题就暂时不做了哈

今天 这道题,首先如果有一个字母出现次数达到了(字符串长度+1)/2,那就一定不能形成。。

然后使用大根队来维护出现次数最多的元素。

每次取出大根队里最顶端的两个,交替形成字符串,如果取出后,字符出现次数仍不为0,那就把它放回去,如此反复直到只剩一个元素,或者没有。

Java代码

class Solution {
     public String reorganizeString(String S) {
        int []count=new int[26];
        int maxamount=Integer.MIN_VALUE;
        int len=S.length();
        for (int i = 0; i < len; i++) {
            count[S.charAt(i)-'a']++;
            maxamount=Math.max(maxamount,count[S.charAt(i)-'a']);
        }
        if(maxamount>(len+1)/2){
            return  "";
        }

        PriorityQueue <Character>heap=new PriorityQueue(new Comparator<Character>() {
            @Override
            public int compare(Character c1, Character c2) {
                return count[c2-'a']-count[c1-'a'];
            }
        });
        for (char c='a';c<='z';c++){
            if(count[c-'a']>0){
                    heap.offer(c);
            }
        }
        StringBuffer sb=new StringBuffer();
        while (heap.size()>1){
            char char1=heap.poll();
            char char2=heap.poll();
            sb.append(char1);
            sb.append(char2);
            int index1=char1-'a',index2=char2-'a';
            count[index1]--;
            count[index2]--;
            if(count[index1]>0){
                heap.offer(char1);
            }
            if(count[index2]>0){
                heap.offer(char2);
            }
            
        }
        if(heap.size()>0){
            sb.append(heap.poll());
        }
        return  sb.toString();

    }
}

我们元旦见

我的leetcode代码都已经上传到我的git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值