From 8f269ef2b1c2da6551dcf97f8c21cf50387bf447 Mon Sep 17 00:00:00 2001 From: gameloader Date: Tue, 5 Mar 2024 11:09:20 +0800 Subject: [PATCH] add leetcode content --- content/posts/leetcode.md | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index d5fce6f..6f359f1 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -518,3 +518,54 @@ func bagOfTokensScore(tokens []int, power int) int { ### 总结 在实现过程中, 起初使用一个数组来保存每次的score值, 这样空间复杂度略大, 后来查看他人代码, 发现只需要一个max变量来保存当前最大的score值, 并在每次循环计算当前轮次的score值时与当前的最大值比较并根据二者大小更新max变量的值即可, 这样只需要O(1)的空间复杂度. + +## day8 2024-03-05 + +### 1750. Minimum Length of String After Deleting Similar Ends + +Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: + +1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal. +2. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. +3. The prefix and the suffix should not intersect at any index. +4. The characters from the prefix and suffix must be the same. +5. Delete both the prefix and the suffix. + Return the minimum length of s after performing the above operation any number of times (possibly zero times). + +![0305Qc2qNiDBOKRk](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0305Qc2qNiDBOKRk.png) + +### 题解 + +本题的题目略显复杂, 读起来乍一看让人不明所以, 实际上题目的目标即为从字符串的前后同时删除相同的字符, 删除时只要是相同的就全部删除, 如最前面有一个a最后面有3个a则同时将这四个a删除. 删除的字符串下标不能相交. 思路比较简单, 判断字符串的前后字符是否相同, 然后删除前后的连续相同字符即可, 注意下标不要重叠. 同时注意边界情况, 字符串只有一个字符的情况单独处理一下(直接返回1). + +### 代码 + +```go +func minimumLength(s string) int { + forward := 0 + backward := 0 + for s[0] == s[len(s)-1]{ + if len(s) == 1{ + return 1 + } else { + forward = 0 + backward = len(s)-1 + for forwardforward && s[backward-1] == s[backward] { + backward-- + } + if forward == backward{ + return 0 + } + s = s[forward+1:backward] + } + } + return len(s) +} +``` + +### 总结 + +本题值得注意的地方在于for循环中条件的设置, 可能会忽略与运算符两侧条件表达式的前后顺序, 但由于短路机制的存在, 与运算符两侧表达式的前后顺序有时非常重要, 例如在本题中, 如果将forward