leetcode - 3223. Minimum Length of String After Operations

Description

You are given a string s.

You can perform the following process on s any number of times:

  • Choose an index i in the string such that there is at least one character to the left of index i that is equal to si, and at least one character to the right that is also equal to si.
  • Delete the closest character to the left of index i that is equal to si.
  • Delete the closest character to the right of index i that is equal to si.

Return the minimum length of the final string s that you can achieve.

Example 1:

复制代码
Input: s = "abaacbcbb"

Output: 5

Explanation:
We do the following operations:

Choose index 2, then remove the characters at indices 0 and 3. The resulting string is s = "bacbcbb".
Choose index 3, then remove the characters at indices 0 and 5. The resulting string is s = "acbcb".
Example 2:

Input: s = "aa"

Output: 2

复制代码
Explanation:
We cannot perform any operations, so we return the length of the original string.

Constraints:

复制代码
1 <= s.length <= 2 * 10^5
s consists only of lowercase English letters.

Solution

Because we only need to get the minimum length of the string, so we don't actually need to decide which character we need to delete. Just count the frequency of all characters, and then for anything above 2, if it's an odd number, we have 1 (keep deleting 2s until it's below 3), for even numbers, we have 2 (keep deleting 2s until it's below 3). Add those numbers up and we have our result.

Update: for frequencies below 3, it's the same: for 1 we add 1, for 2 we add 2.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( n ) ≈ o ( 1 ) o(n) \approx o(1) o(n)≈o(1), because we have at most 26 lowercase characters.

Code

python3 复制代码
class Solution:
    def minimumLength(self, s: str) -> int:
        ch_cnt = collections.Counter(s)
        res = 0
        for ch, cnt in ch_cnt.items():
            res += (1 if cnt & 1 == 1 else 2)
        return res
相关推荐
装不满的克莱因瓶14 分钟前
【SpringAI Alibaba】ReactAgent记忆管理MessageTrimmingHook与MessageDeletionHook
java·人工智能·ai·ai编程·springai·springaialibaba
文丑颜不良啊26 分钟前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊31 分钟前
LeetCode2321~2340题目解析
java·leetcode
驭渊的小故事1 小时前
Spring AOP 核心概念与通知类型详解
java·后端·spring
vipxieliang1 小时前
ValidX vs 手写验证代码:开发效率对比实测
java·spring boot·后端
青少儿编程课堂1 小时前
蓝桥杯青少组图形化 STEMA 省考(报名倒计时·11/22开考)+ 全国青少年信息素养大赛 2026—2027赛季 + 电子学会图形化考级:校园华容道大闯关
c++·python·算法·bfs·信息学竞赛
vipxieliang1 小时前
虚拟线程与 GraalVM:Spring Boot 3.x 云原生性能跃迁
java·spring boot·后端
Rain的Java大神之路1 小时前
面试官最烦的答案:“我用 Redis + Token”!接口幂等 8 种方案 + 四层防御,把重复扣款工单干到 0
java·后端·面试
在猴站学算法2 小时前
(《统计学习方法》(第2版) 李航)第2章 感知机算法
学习·算法·机器学习·统计学习