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
相关推荐
探索java2 分钟前
Tomcat Server 组件原理
java·后端·tomcat
勿在浮沙筑高台2 分钟前
无法获取实体类com.example.springdemo2.entity.po.UserPO对应的表名!
java·spring boot·mybatis
wow_DG9 分钟前
【C++✨】多种 C++ 解法固定宽度右对齐输出(每个数占 8 列)
开发语言·c++·算法
Epiphany.55619 分钟前
c++最长上升子序列长度
c++·算法·图论
用户83562907805123 分钟前
Java使用Spire.Doc实现Word转PDF:格式精准的自动化解决方案
java
陆小叁35 分钟前
基于Flink CDC实现联系人与标签数据实时同步至ES的实践
java·elasticsearch·flink
CHEN5_0236 分钟前
【Java基础】反射,注解,异常,Java8新特性,object类-详细介绍
java·开发语言
Cx330❀1 小时前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
云间月13141 小时前
飞算JavaAI智慧文旅场景实践:从景区管理到游客服务的全链路系统搭建
java·开发语言
盖世英雄酱581361 小时前
必须掌握的【InheritableThreadLocal】
java·后端