【每日一题Day366】LC2103环和杆 | 状态压缩

环和杆【LC2103】

总计有 n 个环,环的颜色可以是红、绿、蓝中的一种。这些环分别穿在 10 根编号为 0 到 9 的杆上。

给你一个长度为 2n 的字符串 rings ,表示这 n 个环在杆上的分布。rings 中每两个字符形成一个 颜色位置对 ,用于描述每个环:

  • 第 i 对中的 第一个 字符表示第 i 个环的 颜色 ('R'、'G'、'B')。
  • 第 i 对中的 第二个 字符表示第 i 个环的 位置 ,也就是位于哪根杆上('0' 到 '9')。

例如,"R3G2B1" 表示:共有 n == 3 个环,红色的环在编号为 3 的杆上,绿色的环在编号为 2 的杆上,蓝色的环在编号为 1 的杆上。

找出所有集齐 全部三种颜色 环的杆,并返回这种杆的数量。

  • 思路

    使用状态压缩记录每个杆子的环颜色信息,如果有用三种颜色那么状态值为7;最后计数返回结果

  • 实现

    java 复制代码
    class Solution {
        public int countPoints(String rings) {
            int[] mask = new int[10];
            Map<Character, Integer> map = new HashMap<>();
            map.put('R', 1);
            map.put('G', 2);
            map.put('B', 4);
            for (int i = 0; i < rings.length(); i += 2){
                int val = map.get(rings.charAt(i));
                int index = rings.charAt(i + 1) - '0';
                mask[index] |= val;
            }
            int res = 0;
            for (int i = 0; i < 10; i++){
                if (mask[i] == 7){
                    res++;
                }
            }
            return res;
        }
    }
    • 复杂度
      • 时间复杂度: O ( n ) \mathcal{O}(n) O(n)
      • 空间复杂度: O ( C ) \mathcal{O}(C) O(C)
相关推荐
Shaoshing1 小时前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊2 小时前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing3 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode
海绵宝宝转agent4 小时前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先
Rain的Java大神之路4 小时前
面试被LeetCode 27(移除元素)问懵?别再用两层 for 循环了:一道“简单题”吃透双指针原地删除,附面试加分话术 + 11 个避坑清单
后端·leetcode·面试
重生之小比特6 小时前
【算法拾光】前缀和|连续的子数组和 + 和相同的二元子数组
算法·leetcode·哈希算法
Pniubi6 小时前
力扣 102二叉树的层序遍历(广度优先搜索)
leetcode·宽度优先
一去不复返的通信er6 小时前
力扣15:盛最多水的容器
算法·leetcode
Navigator_Z6 小时前
LeetCode //C - 1309. Decrypt String from Alphabet to Integer Mapping
c语言·算法·leetcode
文丑颜不良啊6 小时前
LeetCode1281~1300题目解析
java·leetcode