From 30134238324bf76a193623513dedfc19905cd96e Mon Sep 17 00:00:00 2001 From: gameloader Date: Fri, 22 Nov 2024 17:53:17 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 150 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 9909c34..620aeb7 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -18032,3 +18032,153 @@ public: } }; ``` + +## day257 2024-11-20 + +### 2516. Take K of Each Character From Left and Right + +You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s. + +Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character. + +![1120GQzlFRPPMxa3](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/1120GQzlFRPPMxa3.png) + +### 题解 + +本题要求返回能取得k个a,b,c字符需要的最少拿取次数,并不能使用贪心,因为选择从左面或者右面拿取字符会影响后面能得到目标结果时拿取的总个数,如左右都是字符a,但左侧第二个字符是b,右侧第二个字符是a,如果只需要每个字符拿1个,拿左侧的a后就可以继续拿取左侧的b,但若拿取右侧的a则想拿取b就要再拿掉左侧的a后才能拿到b。 + +因此需要考虑左侧的选择会对右侧的选择造成什么影响,要把这种影响全部找出来并记录下来。因此可以找到刚好可以满足题目条件的左侧数组的长度,并将左侧指针指向这个子数组的末尾,在此情况下,当左侧指针向左移动时,左侧数组会不满足题目条件,因此需要右侧数组来补充缺少的字符使得总体满足题目条件,因此右侧指针向左移动直到移动过的部分的右侧数组包含的字符和左侧数组包含的字符和满足题目条件。计算此时左右子数组的长度和,如此反复,直到左侧指针移动到数组开头。 + +但有可能数组本身就不可能满足题目要求,因此要先判断一下数组中存在的各个字符的个数,如果不满足要求直接返回-1。 + +### 代码 + +```cpp + +class Solution { +public: + int takeCharacters(string s, int k) { + int ca=0,cb=0,cc=0; + int n=s.size(); + int ans=n; + for(int i=0;i=0){ + if(s[i]=='a') ca--; + if(s[i]=='b') cb--; + if(s[i]=='c') cc--; + while(ca>& guards, vector>& walls) { + vector> cells(m,vector(n,0)); + for (auto wall : walls){ + cells[wall[0]][wall[1]] = 3; + } + int guardpos = 0; + int direction[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; + for (auto guard : guards){ + cells[guard[0]][guard[1]] = 2; + } + for (auto guard : guards){ + for(int i=0;i<4;i++){ + int pos[2] = {guard[0]+direction[i][0], guard[1]+direction[i][1]}; + while(pos[0]>=0&&pos[0]=0&&pos[1]>& matrix) { + unordered_map count; + int m = matrix.size(), n = matrix[0].size(); + + for (const auto& row : matrix) { + string pattern(n, '0'); + string flipped(n, '0'); + + for (int j = 0; j < n; j++) { + pattern[j] = row[j] + '0'; + flipped[j] = (1 - row[j]) + '0'; + } + + count[min(pattern, flipped)]++; + } + + int maxCount = 0; + for (const auto& [_, cnt] : count) { + maxCount = max(maxCount, cnt); + } + return maxCount; + } +}; + +```