[LeetCode] 567. Permutation in String

這一題同樣是定長度的 sliding window,window size 為 s1.size() class Solution { public: bool checkInclusion(string s1, string s2) { unordered_map<char,int> map, map2; int k = s1.size(); int n = s2.size(); if (k > n) return false; int valid = 0; for (const auto& c : s1) map[c]++; for (int i = 0; i < k; i++) { if (!map.count(s2[i])) continue; if (++map2[s2[i]] == map[s2[i]]) valid++; } if (valid == map.size()) return true; for (int i = k; i < n; i++) { if (map.count(s2[i]) && ++map2[s2[i]] == map[s2[i]]) valid++; if (map.count(s2[i-k]) && map2[s2[i-k]]-- == map[s2[i-k]]) valid--; if (valid == map.size()) return true; } return false; } };

October 28, 2022 · 1 分鐘 · Rain Hu

[LeetCode] 1888. Minimum Number of Flips to Make the Binary String Alternating

難度分: 2006 這一題如果沒有條件一,則很簡單,根據奇偶數索引位置,判斷是否要 flip 就可以了。 int minFlips(string s) { int n = s.size(); int ans1 = 0, ans2 = 0; for (int i = 0; i < n; i++) { if ((i % 2 == 0 && s[i] != '1') || (i % 2 == 1 && s[i] != '0')) ++ans1; if ((i % 2 == 0 && s[i] != '0') || (i % 2 == 1 && s[i] != '1')) ++ans2; } int ans = min(ans1, ans2); } 但這一題加上條件一,可以用很精巧的手法,把它轉成 sliding window 的問題,將字串重覆兩次,以原字串長度作為 window size,可解這題。 class Solution { public: int minFlips(string s) { int k = s.size(); s += s; int ans1 = 0, ans2 = 0; for (int i = 0; i < k; i++) { if ((i % 2 == 0 && s[i] != '1') || (i % 2 == 1 && s[i] != '0')) ++ans1; if ((i % 2 == 0 && s[i] != '0') || (i % 2 == 1 && s[i] != '1')) ++ans2; } int ans = min(ans1, ans2); for (int i = k; i < s.size(); i++) { if ((i % 2 == 0 && s[i] != '1') || (i % 2 == 1 && s[i] != '0')) ++ans1; if ((i % 2 == 0 && s[i] != '0') || (i % 2 == 1 && s[i] != '1')) ++ans2; if (((i - k) % 2 == 0 && s[i - k] != '1') || ((i - k) % 2 == 1 && s[i - k] != '0')) --ans1; if (((i - k) % 2 == 0 && s[i - k] != '0') || ((i - k) % 2 == 1 && s[i - k] != '1')) --ans2; ans = min({ans1, ans2, ans}); } return ans; } };

October 28, 2022 · 2 分鐘 · Rain Hu

[Leetcode] 14. Longest Common Prefix

14. Longest Common Prefix Hardness: \(\color{green}\textsf{Easy}\) Ralated Topics: String 一、題目 Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = [“flower”, “flow”, “flight”] Output: “fl” Example 2: Input: strs = [“dog”, “racecar”, “car”] Output: "" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters. 二、分析 簡單的字串比對問題。 需熟悉 string 的函數 substr() 的使用方式,常用以下兩種 s.substr(int start, int len),從 start 起取長度為 len 的子字串。 s.substr(int start) 從 start 起取到字串的結尾。 三、解題 1. String Time complexity: \(O(m\times n),\text{m }為\text{ strs }的長度,\text{n }為\text{ strs[i] }的長度\), Space complexity: \(O(1)\) string longestCommonPrefix(vector<string>& strs) { string res = strs[0]; for (int i = 1; i < strs.size(); i++) { int j = 0; for (; j < min(strs[i].length(), res.length()); j++) { if (strs[i][j] != res[j]) break; } res = res.substr(0, j); } return res; } 回目錄 Catalog ...

October 28, 2022 · 1 分鐘 · Rain Hu

[Leetcode] 13. Roman to Integer

13. Roman to Integer Hardness: \(\color{green}\textsf{Easy}\) Ralated Topics: Hash Table、Math、String 一、題目 Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. \(\boxed{\begin{array}{ll} \textbf{Symbol}&\textbf{Value}\\ \texttt{I}&1\\ \texttt{V}&5\\ \texttt{X}&10\\ \texttt{L}&50\\ \texttt{C}&100\\ \texttt{D}&500\\ \texttt{M}&1000\\ \end{array}}\) For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: ...

October 27, 2022 · 2 分鐘 · Rain Hu

[Leetcode] 835. Image Overlap

835. Image Overlap Hardness: \(\color{orange}\textsf{Medium}\) Ralated Topics: Array、Matrix 一、題目 You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix bordered are erased. Return the largest possible overlap. ...

October 27, 2022 · 3 分鐘 · Rain Hu

[LeetCode] 2653. Sliding Subarray Beauty

難度分: 1786 我覺得這一題稍有難度,主要在處理 findKth 方法時,有一些技巧,如果單純用 vector 來記錄 window,會 LTE,因為 nums[i] 的範圍滿小的(-50~50之間),可以用 bucket sort,如果數字再更大一點,可以使用 fenwick tree 或是 segment tree 範圍求和,使 update 與 query 的複雜度都是 \(\log(n)\) Bucket Sort class NumberTracker { public: virtual void update(int num, int delta) = 0; virtual int findKth(int k) = 0; virtual ~NumberTracker() {} }; class BucketSort : public NumberTracker { private: vector<int> cnt; int left_; int right_; int n_; public: BucketSort(int left, int right) { left_ = left; right_ = right; n_ = right - left + 1; cnt.assign(n_, 0); } void update(int num, int delta) override { cnt[num - left_] += delta; } int findKth(int k) override { int total = 0; for (int i = 0; i <= n_; i++) { total += cnt[i]; if (total >= k) { return i + left_; } } return -1; } }; class Solution { private: unique_ptr<NumberTracker> tracker; public: Solution() : tracker(make_unique<BucketSort>(-50, 50)) {} vector<int> getSubarrayBeauty(vector<int>& nums, int k, int x) { int n = nums.size(); vector<int> res; for (int i = 0; i < k; i++) { tracker->update(nums[i], 1); } int ans = tracker->findKth(x); res.push_back(min(ans, 0)); for (int i = k; i < n; i++) { tracker->update(nums[i-k], -1); tracker->update(nums[i], 1); ans = tracker->findKth(x); res.push_back(min(ans, 0)); } return res; } }; Fenwick Tree class FenwickTree : public NumberTracker { private: int left_; int right_; int n_; vector<int> bit; int lowbit(int a) { return a & (-a); } void add(int idx, int diff) { idx++; int n = bit.size(); while (idx < n) { bit[idx] += diff; idx += lowbit(idx); } } int query(int idx) { int sum = 0; idx++; while (idx > 0) { sum += bit[idx]; idx -= lowbit(idx); } return sum; } public: FenwickTree(int left, int right) { left_ = left; right_ = right; n_ = right - left + 1; bit.assign(n_ + 1, 0); } void update(int num, int delta) { num -= left_; add(num, delta); } int findKth(int k) { int left = 0; int right = n_; while (left < right) { int mid = (left + right) >> 1; if (query(mid) >= k) right = mid; else left = mid + 1; } return min(0, left + left_); } }; Segment Tree (zkw tree) class NumberTracker { public: virtual void build(vector<int> nums) = 0; virtual void update(int num, int delta) = 0; virtual int findKth(int k) = 0; virtual ~NumberTracker() {} }; class SegmentTree : public NumberTracker { private: int n_; int m_; vector<int> tree_; unordered_map<int,int> num_to_idx; unordered_map<int,int> idx_to_num; int lowbit(int a) { return a & (-a); } public: SegmentTree() {} void build(vector<int> nums) override { sort(nums.begin(), nums.end()); for (int i = 0, j = 0; i < nums.size(); i++) { if (i > 0 && nums[i] == nums[i-1]) continue; num_to_idx[nums[i]] = j; idx_to_num[j++] = nums[i]; } for (n_ = 1; n_ < num_to_idx.size(); n_ <<= 1); m_ = n_ << 1; tree_.assign(m_, 0); } void update(int num, int delta) override { int idx = num_to_idx[num]; idx += n_; while (idx > 0) { tree_[idx] += delta; idx >>= 1; } } int findKth(int k) override { int idx = 1; while (idx < n_) { idx <<= 1; if (tree_[idx] < k) { k -= tree_[idx]; idx++; } } return idx_to_num[idx - n_]; } }; class Solution { private: unique_ptr<NumberTracker> tracker; public: Solution() : tracker(make_unique<SegmentTree>()) {} vector<int> getSubarrayBeauty(vector<int>& nums, int k, int x) { tracker->build(nums); int n = nums.size(); vector<int> res; for (int i = 0; i < k; i++) { tracker->update(nums[i], 1); } int ans = tracker->findKth(x); res.push_back(min(ans, 0)); for (int i = k; i < n; i++) { tracker->update(nums[i-k], -1); tracker->update(nums[i], 1); ans = tracker->findKth(x); res.push_back(min(ans, 0)); } return res; } };

October 27, 2022 · 3 分鐘 · Rain Hu

[Leetcode] 12. Integer to Roman

12. Integer to Roman Hardness: \(\color{orange}\textsf{Medium}\) Ralated Topics: Hash Table、Math、String 一、題目 Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. \(\boxed{\begin{array}{ll} \textbf{Symbol}&\textbf{Value}\\ \texttt{I}&1\\ \texttt{V}&5\\ \texttt{X}&10\\ \texttt{L}&50\\ \texttt{C}&100\\ \texttt{D}&500\\ \texttt{M}&1000\\ \end{array}}\) For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: ...

October 26, 2022 · 2 分鐘 · Rain Hu

[Leetcode] 11. Container With Most Water

11. Container With Most Water Hardness: \(\color{orange}\textsf{Medium}\) Ralated Topics: Array、Two Pointer、Greedy 一、題目 You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notive that you may not slant the container. ...

October 26, 2022 · 2 分鐘 · Rain Hu

[Leetcode] 10. Regular Expression Matching

10. Regular Expression Matching Hardness: \(\color{red}\textsf{Hard}\) Ralated Topics: String、Dynamic Programming、Recursion 一、題目 Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example 1: Input: s = “aa”, p = “a” Output: false Explanation: “a” does not match the entire string “aa”. Example 2: ...

October 26, 2022 · 3 分鐘 · Rain Hu

[LeetCode] 2134. Minimum Swaps to Group All 1's Together II

難度分: 1748 遇到 circular 的問題都可以換位思考,這題可以想成「min swaps to group all 1」或「min swaps to group all 0」 class Solution { public: int minSwaps(vector<int>& nums) { int n = nums.size(); int k = accumulate(nums.begin(), nums.end(), 0); return min(minSwapsHelper(nums, 1, k), minSwapsHelper(nums, 0, n-k)); } int minSwapsHelper(vector<int>& nums, int target, int k) { int n = nums.size(); int curr = 0; for (int i = 0; i < k; i++) { if (nums[i] == target) curr++; } int cnt = curr; for (int i = k; i < n; i++) { if (nums[i] == target) curr++; if (nums[i-k] == target) curr--; cnt = max(cnt, curr); } return k - cnt; } };

October 26, 2022 · 1 分鐘 · Rain Hu