当前位置:网站首页>Winter vacation daily question - maximum number of balloons

Winter vacation daily question - maximum number of balloons

2022-07-06 15:17:00 A cat that doesn't eat mice

 Give you a string  text, You need to use  text  To piece together as many words as possible  "balloon"( balloon ).

 character string  text  Each letter in can only be used once at most . Please return the maximum number of words you can piece together  "balloon".
  • Example

image-20220213131341904

 Input :text = "loonbalxballpoon"
 Output :2

Ideas

Statistical letters b,a,l,o,n Number of occurrences of , Choose the one with the least number of occurrences ( Be careful :o , l When comparing, divide by 2)

  • Code
 public int maxNumberOfBalloons(String text) {
    
     // Count the number of each word 
     int[] nums = new int[26];
     char[] chars = text.toCharArray();
     for (char c : chars) {
    
         int i = c - 'a';
         nums[i]++;
     }
     int min = nums[0];
     for (int i = 0; i < nums.length; i++) {
    
         if (i+'a'=='b' || i+'a'=='n')
             min = Math.min(min,nums[i]);
         if (i+'a'=='l' || i+'a'=='o')
             min = Math.min(min,nums[i]/2);
     }
     return min;
 }
原网站

版权声明
本文为[A cat that doesn't eat mice]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131320337660.html