LeetCode每日一题(1737. Change Minimum Characters to Satisfy One of Three Conditions)

You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.

Your goal is to satisfy one of the following three conditions:

Every letter in a is strictly less than every letter in b in the alphabet.
Every letter in b is strictly less than every letter in a in the alphabet.
Both a and b consist of only one distinct letter.
Return the minimum number of operations needed to achieve your goal.

Example 1:

Input: a = “aba”, b = “caa”
Output: 2

Explanation: Consider the best way to make each condition true:

  1. Change b to “ccc” in 2 operations, then every letter in a is less than every letter in b.
  2. Change a to “bbb” and b to “aaa” in 3 operations, then every letter in b is less than every letter in a.
  3. Change a to “aaa” and b to “aaa” in 2 operations, then a and b consist of one distinct letter.
    The best way was done in 2 operations (either condition 1 or condition 3).

Example 2:

Input: a = “dabadd”, b = “cda”
Output: 3

Explanation: The best way is to make condition 1 true by changing b to “eee”.

Constraints:

  • 1 <= a.length, b.length <= 105
  • a and b consist only of lowercase letters.

先分别计算 a 和 b 中各字母出现的频次, 然后把按每个字母作为分隔的情况下, 需要挪动的字母数量都计算出来取最小值, 当然还有如果都挪到同一个字母, 那需要选择出现最多频次的字母


impl Solution {
    pub fn min_characters(a: String, b: String) -> i32 {
        let counts_a = a.chars().fold(vec![0; 26], |mut l, c| {
            l[c as usize - 97] += 1;
            l
        });
        let counts_b = b.chars().fold(vec![0; 26], |mut l, c| {
            l[c as usize - 97] += 1;
            l
        });
        let length = (a.len() + b.len()) as i32;
        let mut a_left_b_right = i32::MAX;
        let mut a_right_b_left = i32::MAX;
        let mut only_one = i32::MAX;
        for i in 1..26 {
            a_left_b_right = a_left_b_right.min(
                counts_a[..i].into_iter().sum::<i32>() + counts_b[i..].into_iter().sum::<i32>(),
            );
            a_right_b_left = a_right_b_left.min(
                counts_b[..i].into_iter().sum::<i32>() + counts_a[i..].into_iter().sum::<i32>(),
            );
        }
        for i in 0..26 {
            only_one = only_one.min(length - counts_a[i] - counts_b[i]);
        }
        a_left_b_right.min(a_right_b_left).min(only_one)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值