使得字符串a所有字符均小于字符串b,所需要改变的次数,a,b均只含有小写字母

在这里插入图片描述
这道题看似比较难,实际上只要有思路就可以很快写出来。以a 小于 b为例。
假设字母表中的第i位为a的上界,则b的上界应该为i+1。a的上界最多为y,因为a需要严格小于b。如果a的上界为i,则a从i + 1开始的元素就需要改变。则a需要改变的次数为countA[i+1]到count[26]的累加。同理,b需要改变的元素个数为countB[0]到count[i]的累加,使其都严格大于字母表第i个元素。

在这里插入图片描述

/**
 * @author: Xie
 * @Description: TODO
 * @Date: 2021/1/24 10:59
 */
public class test2 {
    public static void main(String[] args){
        System.out.print(minCharacters("gwegergwgwwje", "dsfghkehrgosiehrgoheorghoeirg"));
    }
    public static int minCharacters(String a, String b) {
        int[] countA = new int[26];
        int[] countB = new int[26];
        // 构建字符串的Hash,按字母表统计过a和b中每个字符的数目
        for (int i = 0; i < a.length(); i++){
            countA[(int)a.charAt(i) - 97]++;
        }
        for (int i = 0; i < b.length(); i++){
            countB[(int)b.charAt(i) - 97]++;
        }
        int min;
        int n1 = aMinB(countA, countB, a.length());
        int n2 = bMinA(countA, countB, b.length());
        min = Math.min(n1, n2);
        int n3 = ab(a, b, countA, countB);
        min = Math.min(min, n3);
        return min;
    }
    // a 所有均小于 b
    public static int aMinB(int[] countA, int[] countB, int totalA){
        // 遍历a的上界
        int min = Integer.MAX_VALUE;
        int totalB = 0;

        for (int i = 0; i < 25; i++){
            // a上界是i,则b的下界是i + 1
            totalA -= countA[i];
            totalB += countB[i];
            min = Math.min(min, totalA + totalB);
        }
        return min;
    }
    // b 所有均小于 a
    public static int bMinA(int[] countA, int[] countB, int totalB){
        // 遍历a的上界
        int min = Integer.MAX_VALUE;
        int totalA = 0;
        for (int i = 0; i < 25; i++){
            // b上界是i,则a的下界是i + 1
            totalB -= countB[i];
            totalA += countA[i];
            min = Math.min(min, totalA + totalB);
        }
        return min;
    }
    public static int ab(String a, String b, int[] countA, int[] countB){
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < 26; i++){
            // 全转为第i个字符
            int temp = a.length() - countA[i] + b.length() - countB[i];
            min = Math.min(min, temp);
        }
        return min;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值