【Leetcode】1189. Maximum Number of Balloons

題目地址:

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

給定一個字符串,問其中字母可以組成多少個單詞balloonballoon

思路是直接數字符串裏含多少b,a,l,o,nb,a,l,o,n,然後從b,a,nb,a,n的出現次數取最小,再從l,ol,o的出現次數中除以22後再取最小,兩個最小再取最小即爲答案。代碼如下:

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)

正確性證明可以用夾逼的辦法來證明,先證明不可能產生比resres更多的balloonballoon,再證明上面的方法可以產生可以產生resres個即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章