每日力扣-哈希-气球的数量

96 阅读1分钟

给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。

字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。

输入:text = "nlaebolko" 输出:1

解题思路:先统计b a l o n各有几个,每出一个减balloon直到不合规则

class Solution {
public:
    int maxNumberOfBalloons(string text) {
        vector<int> hash(26,0);
        for(int i = 0 ; i < text.size() ; i++)
        {
            hash[text[i] - 'a'] ++;
        }
        int count = 0;
        while(jugde(hash))
        {
            del(hash);
            count ++;
        }
        return count;
    }
    void del(vector<int>& hash)
    {
        hash['a'-'a'] --;
        hash['b'-'a'] --;
        hash['l'-'a'] --;
        hash['l'-'a'] --;
        hash['o'-'a'] --;
        hash['o'-'a'] --;
        hash['n'-'a'] --;
    }
    bool jugde(vector<int> hash)
    {
        if(hash['a'-'a'] <= 0) return false;
        if(hash['b'-'a'] <= 0) return false;
        if(hash['l'-'a'] <= 1) return false;
        if(hash['o'-'a'] <= 1) return false;
        if(hash['n'-'a'] <= 0) return false;
        return true;
    }
};