diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index ec65b43..65fc4bc 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -23328,3 +23328,98 @@ public: } }; ``` +## day346 2025-02-19 +### 1415. The k-th Lexicographical String of All Happy Strings of Length n +A happy string is a string that: + +consists only of letters of the set ['a', 'b', 'c']. +s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). +For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. + +Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. + +Return the kth string of this list or return an empty string if there are less than k happy strings of length n. + +![02190AfJG0zCGKft](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/02190AfJG0zCGKft.png) + +### 题解 +本题可以使用回溯法来尝试构建所有可能的满足题目条件的字符串组合,由于构建过程中在每个位置遍历字符是依照字典序遍历的,因此构建过程最终得到的达到题目要求长度的字符串天然满足字典序。则在构建过程中,一旦长度达到要求长度就将计数加一,当计数达到k时直接返回当前构建得到的字符串。否则返回空字符串。 + +### 代码 +```cpp +class Solution { +public: + string getHappyString(int n, int k) { + string current_string; + string result; + int count = 0; + + backtrack(n, k, current_string, count, result); + return result; + } + +private: + void backtrack(int n, int k, string& current_string, int& count, string& result) { + if (current_string.length() == n) { + count++; + if (count == k) { + result = current_string; + } + return; + } + + for (char c : {'a', 'b', 'c'}) { + if (current_string.empty() || current_string.back() != c) { + current_string.push_back(c); + backtrack(n, k, current_string, count, result); + current_string.pop_back(); + + if (count == k) { + return; + } + } + } + } +}; +``` +## day347 2025-02-20 +### 1980. Find Unique Binary String +Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. + +![02202umalWszADa6](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/02202umalWszADa6.png) + +### 题解 +本题考虑字符串仅包含0和1,且字符串长度最大为16,因此可以直接将字符串中的0和1当作二进制位来处理,每个字符串都对应一个二进制串从而可以计算出该串对应的整数,将这些整数保存起来,再从该长度对应的二进制数的整数范围内找到一个不包含在这些整数中的整数转化为字符串形式的二进制串即可得到结果,一种简单的方法是直接从0开始递增遍历,只要碰到的数字不包含在之前的二进制串对应的整数中即为有效数字,因为之前的二进制串对应的整数最多16个,因此最差遍历16次一定可以得到结果。 + +### 代码 +```cpp + +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + int n = nums.size(); + unordered_set s; + for (string& num : nums) { + int val = 0; + for (char c : num) { + val = (val << 1) | (c - '0'); + } + s.insert(val); + } + + for (int i = 0; ; ++i) { + if (s.find(i) == s.end()) { + string res = ""; + int temp = i; + for (int j = 0; j < n; ++j) { + res = (char)((temp & 1) + '0') + res; + temp >>= 1; + } + return res; + } + } + } +}; +``` + +