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 s[i], and at least one character to the right that is also equal to s[i].
  • Delete the closest character to the left of index i that is equal to s[i].
  • Delete the closest character to the right of index i that is equal to s[i].

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
相关推荐
JIngJaneIL几秒前
停车场管理|停车预约管理|基于Springboot的停车场管理系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·停车场管理系统
杰克尼31 分钟前
二分查找为什么总是写错
java·数据结构·算法
半旧夜夏2 小时前
【分布式缓存】Redis持久化和集群部署攻略
java·运维·redis·分布式·缓存
短视频矩阵源码定制2 小时前
矩阵系统源码推荐:技术架构与功能完备性深度解析
java·人工智能·矩阵·架构
Eiceblue2 小时前
使用 Java 将 Excel 工作表转换为 CSV 格式
java·intellij-idea·excel·myeclipse
漂流幻境3 小时前
IntelliJ IDEA的Terminal中执行ping命令时遇到的“No route to host“问题
java·ide·intellij-idea
苹果醋33 小时前
element-ui源码阅读-样式
java·运维·spring boot·mysql·nginx
BUG?不,是彩蛋!3 小时前
IntelliJ IDEA从安装到使用:零基础完整指南
java·ide·intellij-idea
程序员阿鹏3 小时前
56.合并区间
java·数据结构·算法·leetcode
SmoothSailingT3 小时前
IDEA实用快捷键
java·ide·intellij-idea