阿里 LeetCode 1189.“气球“的最大数量

思路:根据题目模拟即可。先统计text中与单词balloon相关的字符数量,由于一个单词需要消耗两个l和o字符,对其统计数量进行除2向下取整,然后所有字符的最小出现次数即是能够凑成balloon的最大数量。

复杂度分析:

1.时间复杂度:假如C为目标字符串的字符种类数量,本题中C = 5,统计text的词频复杂度为O(n),计算答案的复杂度为O(C),因此整体的复杂度为O(n + C)。

2.空间复杂度:O(C)。

附代码:

java 复制代码
class Solution {
    public int maxNumberOfBalloons(String text) {
        int[] cnt = new int[5];
        for(int i = 0;i < text.length();i++){
            char c = text.charAt(i);
            if(c == 'b') cnt[0]++;
            else if(c == 'a') cnt[1]++;
            else if(c == 'l') cnt[2]++;
            else if(c == 'o') cnt[3]++;
            else if(c == 'n') cnt[4]++;
        }
        cnt[2] /= 2;
        cnt[3] /= 2;
        int ans = cnt[0];
        for(int i = 0;i < 5;i++){
            ans = Math.min(ans,cnt[i]);
        }
        return ans;
    }
}

ACM模式:

java 复制代码
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        Solution solution = new Solution();
        int result = solution.maxNumberOfBalloons(text);
        System.out.println(result);
        scanner.close();
    }
}

class Solution {
    public int maxNumberOfBalloons(String text) {
        int[] cnt = new int[5];
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == 'b') cnt[0]++;
            else if (c == 'a') cnt[1]++;
            else if (c == 'l') cnt[2]++;
            else if (c == 'o') cnt[3]++;
            else if (c == 'n') cnt[4]++;
        }
        cnt[2] /= 2;
        cnt[3] /= 2;
        int ans = cnt[0];
        for (int i = 0; i < 5; i++) {
            ans = Math.min(ans, cnt[i]);
        }
        return ans;
    }
}
相关推荐
FPGA信号处理3 分钟前
【模式识别】第四节课:支持向量机
算法·机器学习·支持向量机
碧海银沙音频科技研究院14 分钟前
面向长尾音频分类的知识蒸馏研究
人工智能·算法·音视频
alphaTao1 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
青岚_Nox1 小时前
# C语言实战:函数完全指南——从基础概念到static/extern深度解析
算法
CCCCCCCCharlie1 小时前
深入解析I/O底层:文件描述符与缓冲区真相
linux·开发语言·c++·算法
Cccp.1231 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
学逆向的1 小时前
C 选择结构的执行效率分析
c语言·开发语言·算法·网络安全
wzdark2 小时前
动态规划算法的状态转移矩阵可视化分析5
算法·矩阵·动态规划
Pniubi2 小时前
力扣70爬楼梯
数据结构·算法·leetcode
人工智能培训2 小时前
具身智能环境交互与学习范式原理
大数据·linux·人工智能·学习·算法·机器学习