气球的最大数量
题目描述
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 “balloon”(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 “balloon”。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例:
输入:text = “nlaebolko”
输出:1
题解
遍历字符串,如果字符串长度为0直接返回0。
定义五个变量分别赋初始值0,然后将字符串转换成字符数组,遍历该字符数组
判断数组中是否有b,a,l,o,n如果有将对应的变量+1,
最后返回最小的那个变量的值
public int maxNumberOfBalloons(String text) {
if (text.length() == 0) {
return 0;
}
int b = 0;
int a = 0;
int l = 0;
int o = 0;
int n = 0;
char[] chars = text.toCharArray();
for (char c : chars) {
if (c == 'b') {
b ++;
} else if (c == 'a') {
a ++;
} else if (c == 'l') {
l ++;
} else if (c == 'o') {
o ++;
} else if (c == 'n') {
n ++;
}
}
return Math.min(Math.min(Math.min(b,a),Math.min(l/2,o/2)),n);
}
作者:yi-ge-23
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons/solution/qi-qiu-de-zui-da-shu-liang-by-yi-ge-23/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。