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
相关推荐
pursuit_csdn3 分钟前
LeetCode 916. Word Subsets
算法·leetcode·word
TU.路7 分钟前
leetcode 24. 两两交换链表中的节点
算法·leetcode·链表
昔我往昔24 分钟前
Spring Boot中如何处理跨域请求(CORS)
java·spring boot·后端
昔我往昔28 分钟前
Spring Boot中的配置文件有哪些类型
java·spring boot·后端
qingy_204641 分钟前
【算法】图解排序算法之归并排序、快速排序、堆排序
java·数据结构·算法
张声录11 小时前
【ETCD】【源码阅读】深入探索 ETCD 源码:了解 `Range` 操作的底层实现
java·数据库·etcd
Zhu_S W1 小时前
SpringBoot 自动装配原理及源码解析
java·spring boot·spring
爱晒太阳的小老鼠1 小时前
apisix的etcd使用
java·etcd
西岸风1661 小时前
【全套】基于Springboot的房屋租赁网站的设计与实现
java·spring boot·后端
VX_CXsjNo11 小时前
免费送源码:Java+ssm+Android 基于Android系统的外卖APP的设计与实现 计算机毕业设计原创定制
android·java·css·spring boot·mysql·小程序·idea