阿里 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;
    }
}
相关推荐
YLCHUP8 分钟前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴1 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu5 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu6 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_7 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏8 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
饮水桶_T10 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T12 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥13 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm
开开心心就好14 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua