阿里 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;
    }
}
相关推荐
可编程芯片开发9 小时前
UPFC统一潮流控制器的simulink建模与仿真
算法
小小仙子9 小时前
矢量网络分析仪如何测试S参数的?
人工智能·算法·机器学习
中微极客11 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
storyseek11 小时前
前缀和实现Kogge-Stone算法
数据结构·算法
元Y亨H12 小时前
开发者必须掌握的十大核心算法
算法
元Y亨H12 小时前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法
元Y亨H12 小时前
数据结构与算法的通俗指南
数据结构·算法
2301_7644413312 小时前
用动力学系统(微分方程)为 Kernberg 的客体关系单元提供数学化的操作定义,把“自体—客体“这对心理结构建模成一个二维耦合系统
数据结构·python·算法·数学建模
林泽毅12 小时前
PyTRIO快速入门(二):Datum构建
人工智能·算法·产品
keep intensify13 小时前
最长有效括号
算法·leetcode·动态规划