LeetCode 2103.环和杆

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

C++代码

常规

cpp 复制代码
class Solution {
public:
    int countPoints(string rings) {
        int count = 0;
        set<string>se[10];
        for(int i=1,j=0;i<rings.length();i+=2,j+=2){
            se[rings[i]-'0'].insert(to_string(rings[j]));
        }

        for(int i=0;i<10;i++){
            if(se[i].size()==3) count++;  
        }
        
        return count;
    }
};

Python代码

位运算

python 复制代码
class Solution:
    def countPoints(self, rings: str) -> int:
        n,count = len(rings),0
        binary_map = [0]*17  # R - B = 17
        for i in range(0,n,2):
            binary_map[ord(rings[i]) - ord('B')] |= 1 << (int(rings[i+1]) - int('0'))  
        for i in range(10):
            tmp = 0
            for ch in ['R','G','B']:
                tmp += (binary_map[ord(ch)-ord('B')] >> i) & 1  #第i根杆 上是否有ch颜色的圈
            if tmp == 3:
                count += 1
        return count
相关推荐
zephyr051 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米1 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
卡提西亚3 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结3 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
从零开始的代码生活_3 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法
泷寂4 小时前
最小生成树 (MST基础)
算法
Daniel_1234 小时前
数组——总结篇
算法
不懒不懒4 小时前
【针对路面识别数据集,结合三轴加速度标准化数据及多路面识别需求,以下是算法选择与处理方案】
算法
Reart5 小时前
Leetcode 121. 买卖股票的最佳时机(717)
后端·算法
会编程的小孩5 小时前
初识数据类型以及变量定义
数据结构·算法