题目链接:https://leetcode-cn.com/problems/maximum-number-of-balloons/
执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:39.6 MB, 在所有 Java 提交中击败了10.34% 的用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int maxNumberOfBalloons(String text) { int ans = 0; int[] chars = new int[26]; for (char ch: text.toCharArray()) { chars[ch - 'a']++; } ans = Math.min(chars[0], chars[1]); ans = Math.min(chars['l' - 'a']/2, ans); ans = Math.min(chars['o' - 'a']/2, ans); ans = Math.min(chars['n' - 'a'], ans); return ans; } }
|
执行用时:8 ms, 在所有 Java 提交中击败了27.19% 的用户
内存消耗:40.8 MB, 在所有 Java 提交中击败了5.17% 的用户
java map 新特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int maxNumberOfBalloons(String text) { Map<Character, Integer> map = new HashMap<>(); map.put('a',0); map.put('b',0); map.put('l',0); map.put('n',0); map.put('o',0); for (char ch: text.toCharArray()) { map.computeIfPresent(ch, (key, oldValue) -> oldValue+1); } map.compute('l',(key, oldValue) -> oldValue / 2); map.compute('o',(key, oldValue) -> oldValue / 2); int ans = Collections.min(map.values()); return ans; } }
|