力扣2103环和杆

in 默认分类 with 0 comment

仅需要统计是否存在三个不同的颜色不需要统计环的数量,可以用位图来表示颜色是否存在,每次套上一个新环就用位的或运算,表示添加了该颜色。

class Solution {
    public int countPoints(String rings) {
        //位运算
        int[] zhuzi = new int[10];
        for(int i=0;i<rings.length()/2;++i){
            int color = 0;
            switch(rings.charAt(2*i)){
                case 'R' -> color =4;
                case 'G' -> color =2;
                case 'B' -> color =1;
            };
            int pos = (int)(rings.charAt(2*i+1)-'0');
            zhuzi[pos] |= color;
        }
        int ans = 0;
        for(int i=0;i<10;++i){
            if(zhuzi[i]==7){
                ++ans;
            }
        }
        return ans;
    }
}
Responses