【Leetcode】1189. Maximum Number of Balloons

题目地址:

https://leetcode.com/problems/maximum-number-of-balloons/

给定一个字符串,问其中字母可以组成多少个单词 b a l l o o n balloon balloon

思路是直接数字符串里含多少 b , a , l , o , n b,a,l,o,n b,a,l,o,n,然后从 b , a , n b,a,n b,a,n的出现次数取最小,再从 l , o l,o l,o的出现次数中除以 2 2 2后再取最小,两个最小再取最小即为答案。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int maxNumberOfBalloons(String text) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('b', 0);
        map.put('a', 0);
        map.put('l', 0);
        map.put('o', 0);
        map.put('n', 0);
    
        for (int i = 0; i < text.length(); i++) {
            if (map.containsKey(text.charAt(i))) {
                map.put(text.charAt(i), map.get(text.charAt(i)) + 1);
            }
        }
        
        int res = Integer.MAX_VALUE;
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            char c = entry.getKey();
            if (c == 'b' || c == 'a' || c == 'n') {
                res = Math.min(res, entry.getValue());
            } else {
                res = Math.min(res, entry.getValue() / 2);
            }
        }
        
        return res;
    }
}

时空复杂度 O ( n ) O(n) O(n)

正确性证明可以用夹逼的办法来证明,先证明不可能产生比 r e s res res更多的 b a l l o o n balloon balloon,再证明上面的方法可以产生可以产生 r e s res res个即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值