不需要一次一次的模拟,直接用数学算出可以拼出气球的数量,Python写法:
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
cnt = Counter(ch for ch in text if ch in "balon")
cnt['l'] //= 2
cnt['o'] //= 2
return min(cnt.values()) if len(cnt) == 5 else 0
C++写法,节省空间,只存储需要用到的字符串
class Solution {
public:
int maxNumberOfBalloons(string text) {
vector<int> cnt(5);
for (auto & ch : text) {
if (ch == 'b') {
cnt[0]++;
} else if (ch == 'a') {
cnt[1]++;
} else if (ch == 'l') {
cnt[2]++;
} else if (ch == 'o') {
cnt[3]++;
} else if (ch == 'n') {
cnt[4]++;
}
}
cnt[2] /= 2;
cnt[3] /= 2;
return *min_element(cnt.begin(), cnt.end());
}
};