↓快轉到主要內容

Bit-Manipulation

Bit Manipulation 位元運算
·3 分鐘
演算法 Bit-Manipulation
常用的位元操作、AND 只會減少位元而 OR 只會增加位元、用 n & (n » 1) 找相鄰的 1,以及全部是 1 的數 2^k - 1
Trie 字典樹
·2 分鐘
演算法 Trie String Prefix Bit-Manipulation
用巢狀 dict 建 Trie、在節點上記數量、搭配 DFS 搜尋,以及什麼時候其實不需要 Trie
LeetCode 864: Shortest Path to Get All Keys
·2 分鐘
LeetCode Hard Bfs Bit-Manipulation Matrix
LeetCode 864 解題筆記:BFS 的狀態是 (位置, 拿到的鑰匙遮罩),同一格拿著不同鑰匙是不同的節點
LeetCode 1178: Number of Valid Words for Each Puzzle
·1 分鐘
LeetCode Hard Bit-Manipulation Hash-Map Trie
LeetCode 1178 解題筆記:單字只在乎用了哪些字母,轉成 26-bit 遮罩計數,再枚舉謎題遮罩的所有子集合
LeetCode 3950: Exactly One Consecutive Set Bits Pair
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 3950 解題筆記:n & (n » 1) 的每個 1 代表一對相鄰的 1,剛好一對就是它只有一個 1
LeetCode 3910: Count Connected Subgraphs with Even Node Sum
·1 分鐘
LeetCode Hard Bit-Manipulation Enumeration Graph Union-Find
LeetCode 3910 解題筆記:n 很小,用位元遮罩枚舉所有子集合,先檢查和是不是偶數,再檢查誘導子圖是否連通
LeetCode 3827: Count Monobit Integers
·1 分鐘
LeetCode Easy Bit-Manipulation Enumeration
LeetCode 3827 解題筆記:每一位都一樣的數只有 0 和 2^k - 1;個數就是 (n + 1).bit_length()
LeetCode 2401: Longest Nice Subarray
·1 分鐘
LeetCode Medium Sliding-Window Bit-Manipulation Array
LeetCode 2401 解題筆記:兩兩 AND 為 0 ⇔ 每個 bit 最多被一個數用到;用一個 mask 記錄視窗用掉的 bit,衝突就縮左邊並把它的 bit 拿掉
LeetCode 1763: Longest Nice Substring
·1 分鐘
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 解題筆記:沒有大小寫配對的字元一定不在答案裡,用它切開字串遞迴;長度相同時取左邊的
LeetCode 1461: Check If a String Contains All Binary Codes of Size K
·1 分鐘
LeetCode Medium Hash-Table String Bit-Manipulation Rolling-Hash
LeetCode 1461 解題筆記:把所有長度 k 的子字串丟進集合,大小等於 2^k 就成立;最後一個起點是 len(s) - k
LeetCode 1016: Binary String With Substrings Representing 1 To N
·2 分鐘
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 解題筆記:s 最多 1000 個字元,長度固定時的子字串數量有限,n 太大一定是 False;從 n 往下檢查會很快失敗,或從每個起點往右最多延伸 30 位收集所有 <= n 的值
LeetCode 1486: XOR Operation in an Array
·1 分鐘
LeetCode Easy Math Bit-Manipulation
LeetCode 1486 解題筆記:依定義產生 start + 2i,逐一 XOR 起來