“This is the 27th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
Maximum number of “balloons”
The title
You are given a string text and you need to use the letters in the text to make up as many words as possible for “balloon”.
Each letter in the string text can be used only once at most. Please return the maximum number of words you can piece together with “balloon”.
Example 1
Input: text = "nlaebolkoCopy the code
Example 2
Input: text = "loonbalxballpoon" Output: 2Copy the code
Example 3
Input: text = "leetcode" output: 0Copy the code
Answer key
Statistical simulation
Simple type of problems, directly according to the problem description simulation can be.
- Step 1: Enumerate the string texttexttext, count the number of word strings in texttexttext, and store the number of strings used in mapmapMap
- Enumerate the string balloonballoonballoon, looking up the strings used in the word balloonballoonballoon one by one in the mapmapmap
- There are two L’s, O2 L’s, O2 L’s, and O’s to form a balloonballoonballoon word. Therefore, when l, OL, OL, and O are met, the number of L, OL, OL, and O in the string texttexttext is halved and rounded downward
- So the minimum number of a, b, n, L, oa, b, n, L, oa, b, n, L, O in the string texttexttext is the maximum number that can make up the target word balloonballoonballoon
- Returns the result
Note:
- The number of words is an integer, so when l, OL, ol and O are halved, round down
- The word balloonballoonballoon uses a character that may not exist in texttexttext, so the balloonballoonballoon string needs to be turned to 0 when it is looked up in the mapmapMap
Edit the code as follows:
The complete code
var maxNumberOfBalloons = function(text) {
const map = {};
for(let i = 0 ; i < text.length ; i++){
map[text[i]] = (map[text[i]] || 0) +1
}
const s = 'balloon';
let result = Infinity
for(let i = 0 ; i < s.length ; i++){
if(s[i] === 'l' || s[i] === 'o'){
result = Math.min(result, Math.floor((map[s[i]] || 0) /2))}else{
result = Math.min(result, map[s[i]] || 0)}}return result
};
Copy the code
conclusion
Perhaps the question is too simple, many people can see the answer at a glance. But I think, since it exists, it’s worth recording. Feel free to discuss in the comments section if you have any questions.