Maximum Number of Balloons
#431 in my solved list: https://leetcode.com/problems/maximum-number-of-balloons/
- Count the number of occurrences of the "balloon" letters in the input string
- For "l" and "o", divide the count by 2
- If the balloon string is not fully covered, return 0
- Return the min number across all occurrences
Code is below, cheers, ACC.
public class Solution
{
public int MaxNumberOfBalloons(string text)
{
if (String.IsNullOrEmpty(text)) return 0;
string balloon = "balon";
Hashtable ht = new Hashtable();
foreach (char c in text)
{
if (balloon.Contains(c))
{
if (!ht.ContainsKey(c)) ht.Add(c, 0);
ht[c] = (int)ht[c] + 1;
}
}
string d = "lo";
foreach (char c in d)
{
if (ht.ContainsKey(c))
{
ht[c] = (int)ht[c] / 2;
}
}
if (ht.Count < balloon.Length) return 0;
int min = Int32.MaxValue;
foreach (char c in ht.Keys)
{
min = Math.Min(min, (int)ht[c]);
}
return min;
}
}
Given a string
text
, you want to use the characters of text
to form as many instances of the word "balloon" as possible.
You can use each character in
text
at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko" Output: 1
Example 2:
Input: text = "loonbalxballpoon" Output: 2
Example 3:
Input: text = "leetcode" Output: 0
Constraints:
1 <= text.length <= 10^4
text
consists of lower case English letters only.
- Count the number of occurrences of the "balloon" letters in the input string
- For "l" and "o", divide the count by 2
- If the balloon string is not fully covered, return 0
- Return the min number across all occurrences
Code is below, cheers, ACC.
public class Solution
{
public int MaxNumberOfBalloons(string text)
{
if (String.IsNullOrEmpty(text)) return 0;
string balloon = "balon";
Hashtable ht = new Hashtable();
foreach (char c in text)
{
if (balloon.Contains(c))
{
if (!ht.ContainsKey(c)) ht.Add(c, 0);
ht[c] = (int)ht[c] + 1;
}
}
string d = "lo";
foreach (char c in d)
{
if (ht.ContainsKey(c))
{
ht[c] = (int)ht[c] / 2;
}
}
if (ht.Count < balloon.Length) return 0;
int min = Int32.MaxValue;
foreach (char c in ht.Keys)
{
min = Math.Min(min, (int)ht[c]);
}
return min;
}
}
Comments
Post a Comment