290.删除字符使频率相同

 2423. 删除字符使频率相同 - 力扣(LeetCode)

class Solution {
    public boolean equalFrequency(String word) {
        int theMax=0,theMin=Integer.MAX_VALUE;
        int[] nums=new int[26];
        for(int i=0;i<word.length();i++){
            nums[word.charAt(i)-'a']++;
        }
        Arrays.sort(nums);
        int countNum=0;//统计不同数字
        int countCha=0;//统计不同字母
        if(nums[0]!=0){
            countNum=1;
        }
        for(int i=0;i<26;i++){
            if(i>0&&nums[i-1]!=nums[i]){
                countNum++;
            }
            theMax=Math.max(theMax,nums[i]);
            if(nums[i]!=0){
                theMin=Math.min(theMin,nums[i]);
                countCha++;
            }
        }
        int countOne=0,countMax=0,countMin=0;
        for(int i=0;i<26;i++){
            if(nums[i]==theMax){
                countMax++;
            }
            if(nums[i]==theMin){
                countMin++;
            }
        }
        return (theMax-theMin==1&&countMax==1)||(theMax==1&&theMin==1)||(theMin==1&&countMin==1&&countNum==2)||(countNum==1&&countCha==1);
    }
}
class Solution(object):
    def equalFrequency(self, word):
        the_max = 0
        the_min = float('inf')
        nums = [0] * 26
        for c in word:
            nums[ord(c) - ord('a')] += 1
        nums.sort()
        
        count_num = 0  # count different frequencies
        count_cha = 0  # count different letters
        if nums[0] != 0:
            count_num = 1
        for i in range(26):
            if i > 0 and nums[i-1] != nums[i]:
                count_num += 1
            the_max = max(the_max, nums[i])
            if nums[i] != 0:
                the_min = min(the_min, nums[i])
                count_cha += 1
        
        count_one = 0
        count_max = 0
        count_min = 0
        for num in nums:
            if num == the_max:
                count_max += 1
            if num == the_min:
                count_min += 1
        
        return ((the_max - the_min == 1 and count_max == 1) or 
                (the_max == 1 and the_min == 1) or 
                (the_min == 1 and count_min == 1 and count_num == 2) or 
                (count_num == 1 and count_cha == 1))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值