【每日一题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)
相关推荐
Tisfy32 分钟前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
Navigator_Z1 小时前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
想吃火锅10052 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
All for pursuit.3 小时前
【贪心-2】253.会议室 II
数据结构·c++·算法·leetcode
All for pursuit.17 小时前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
All for pursuit.19 小时前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
blxr_1 天前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
All for pursuit.1 天前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode
blxr_1 天前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展