阿里 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;
    }
}
相关推荐
Dream it possible!1 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 小时前
算法之双指针系列(一)
算法·leetcode
十二1 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
小此方2 小时前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi3 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH3 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi4 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
東隅已逝,桑榆非晚6 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
Eyfcom7 小时前
〖物联网终端实战 01〗UWB 室内高精度定位:仓储 AGV 与人员的厘米级轨迹追踪
物联网·算法·物流系统·快递系统·跨境物流快递系统·物联网终端实战
bro_Java6667 小时前
《排序的底层逻辑:比较、交换与分治》
java·算法·排序算法