1957.删除字符使字符串变好:计数

【LetMeFly】1957.删除字符使字符串变好:计数

力扣题目链接:https://leetcode.cn/problems/delete-characters-to-make-fancy-string/

一个字符串如果没有 三个连续 相同字符,那么它就是一个 好字符串 。

给你一个字符串 s ,请你从 s 删除 最少 的字符,使它变成一个 好字符串

请你返回删除后的字符串。题目数据保证答案总是 唯一的

 

示例 1:

输入:s = "leeetcode"
输出:"leetcode"
解释:
从第一组 'e' 里面删除一个 'e' ,得到 "leetcode" 。
没有连续三个相同字符,所以返回 "leetcode" 。

示例 2:

输入:s = "aaabaaaa"
输出:"aabaa"
解释:
从第一组 'a' 里面删除一个 'a' ,得到 "aabaaaa" 。
从第二组 'a' 里面删除两个 'a' ,得到 "aabaa" 。
没有连续三个相同字符,所以返回 "aabaa" 。

示例 3:

输入:s = "aab"
输出:"aab"
解释:没有连续三个相同字符,所以返回 "aab" 。

 

提示:

  • 1 <= s.length <= 105
  • s 只包含小写英文字母。

解题方法:计数

统计当前字符连续出现了多少个,如果连续出现小于3个则添加到答案字符串中。

  • 时间复杂度$O(len(s))$
  • 空间复杂度:对于可变字符串的编程语言如C++,$O(1)$;对于不可变字符串的编程语言如Python、Golang,$O(len(s))$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
* @Author: LetMeFly
* @Date: 2025-07-21 18:48:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-21 18:51:15
*/
#if defined(_WIN32) || defined(__APPLE__)
#include "_[1,2]toVector.h"
#endif

class Solution {
public:
string makeFancyString(string s) {
string ans;
char last = '0';
int cnt = 0;
for (char c : s) {
if (c == last) {
if (cnt == 2) {
continue;
}
ans += c;
cnt++;
} else {
last = c;
cnt = 1;
ans += c;
}
}
return ans;
}
};

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
* @Author: LetMeFly
* @Date: 2025-07-21 18:48:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-21 18:52:52
*/
#if defined(_WIN32) || defined(__APPLE__)
#include "_[1,2]toVector.h"
#endif

class Solution {
public:
string makeFancyString(string s) {
string ans;
char last = '0';
int cnt = 0;
for (char c : s) {
if (c != last) {
last = c;
cnt = 0;
}
cnt++;
if (cnt < 3) {
ans += c;
}
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'''
Author: LetMeFly
Date: 2025-07-21 18:48:15
LastEditors: LetMeFly.xyz
LastEditTime: 2025-07-21 18:54:53
'''
class Solution:
def makeFancyString(self, s: str) -> str:
ans = []
last = '0'
cnt = 0
for c in s:
if c != last:
last = c
cnt = 0
cnt += 1
if cnt < 3:
ans.append(c)
return ''.join(ans)

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
* @Author: LetMeFly
* @Date: 2025-07-21 18:48:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-21 18:57:03
*/
package main

func makeFancyString(s string) string {
ans := []byte{}
last := byte(0)
cnt := 0
for _, c := range s {
if byte(c) != last {
last = byte(c)
cnt = 0
}
cnt++
if cnt < 3 {
ans = append(ans, byte(c))
}
}
return string(ans)
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


1957.删除字符使字符串变好:计数
https://blog.letmefly.xyz/2025/07/21/LeetCode 1957.删除字符使字符串变好/
作者
发布于
2025年7月21日
许可协议