当前位置:网站首页>[leetcode question brushing day 33] 1189 The maximum number of "balloons", 201. The number range is bitwise AND

[leetcode question brushing day 33] 1189 The maximum number of "balloons", 201. The number range is bitwise AND

2022-07-06 04:14:00 tomly2020

The thirteenth day

1189 “ balloon ” Maximum number of

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”.

Method

Count all letters and... Of the given string balloon Number of relevant letters , The one with the least number of choices is the number of answers .

class Solution {
    
    public int maxNumberOfBalloons(String text) {
    
        int[] cnts = new int[26];
        for (int i = 0; i < text.length(); ++i){
    
            cnts[text.charAt(i) - 'a']++;
        }
        return Math.min(cnts['a' - 'a'], Math.min(cnts['b' - 'a'], Math.min(cnts['l' - 'a'] / 2, Math.min(cnts['o' - 'a'] / 2, cnts['n' - 'a']))));
    }
}

201 Digital range bitwise AND

Here are two integers left and right , Indicates the interval [left, right] , Returns all numbers in this range Bitwise AND Result ( contain leftright Endpoint ).

Method

We start from the lowest position , stay 32 Bit binary number , The lowest value can only be 0 perhaps 1, Because it is bitwise AND , Basis and nature , Only all numbers are not 0 when , Results can be returned 1, So it's easy to know , If left and right It's not equal , Then the binary value in the current position is 0, So we just need to left and right Move one bit to the right , Then judge whether it is equal or not , If equal , Then the binary value on the corresponding bit is 1.

class Solution {
    
    public int rangeBitwiseAnd(int left, int right) {
    
        int cmp = 1;
        int res = 0;
        for (int i = 0; i < 31; ++i){
    
            if (right == left && ((right & 1) == 1)){
    
                res = res | cmp;
            }
            right >>= 1;
            left >>= 1;
            cmp <<= 1;
            if (left == 0 || right == 0) break;
        }
        return res;
    }
}
原网站

版权声明
本文为[tomly2020]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132236328824.html