力扣刷题笔记1189

题号:1189. “气球” 的最大数量

简介:

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

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

题解

本题思想即统计text中的 ‘b’,‘a’,‘l’,‘o’,'n’字符的个数即可
l 和 o的个数需要除以二,最后五个字符个数中最小的即为能拼出"balloon"单词的个数

代码

class Solution {
    public int maxNumberOfBalloons(String text) {
        int b = 0;
        int a = 0;
        int l = 0;
        int o = 0;
        int n = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == 'b') {
                b++;
                continue;
            }
            if (text.charAt(i) == 'a') {
                a++;
                continue;
            }
            if (text.charAt(i) == 'l') {
                l++;
                continue;
            }
            if (text.charAt(i) == 'o') {
                o++;
                continue;
            }
            if (text.charAt(i) == 'n') {
                n++;
                continue;
            }
        }
        l /=2;
        o /=2;
        int []arr = new int[]{b,a,l,o,n};
        Arrays.sort(arr);
        int num = arr[0];
        return num;
    }
}

后来我看到题解中有一个大佬的代码,直呼学到了
他首先创建一个字母表,将text各字符的数量统计出来
然后确定最少字符数量,下面是代码

     int []letters = new int[26];
        for (char ch: text.toCharArray()){
            letters[ch-97] ++;
        }
        letters['l'-97]/=2;
        letters['o'-97]/=2;
        int min = Integer.MAX_VALUE;
        for (char ch : "balon".toCharArray()){
            if (letters[ch-97]<min) {
                min = letters[ch-97];
            }
        }
        return min;
    }

附题解链接
https://leetcode-cn.com/problems/maximum-number-of-balloons/solution/1ms-javati-jiao-zhong-ji-bai-100-zhu-yao-shi-suan-/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值