解题思路
这是一个字符串模拟题,关键点在于:
- 需要重复扫描直到无法消除
- 使用栈来维护当前保留的字符
- 记录连续相同字符的个数
关键点
- 使用栈来处理字符串
- 需要考虑消除后新产生的连续字符
- 重复处理直到字符串不再变化
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string removeRepeated(string s) {
bool changed = true;
while (changed) {
changed = false;
string result;
vector<pair<char, int>> stack; // 字符和其连续出现次数
// 处理每个字符
for (char c : s) {
if (stack.empty() || stack.back().first != c) {
// 新字符,压入栈
stack.push_back({c, 1});
} else {
// 相同字符,增加计数
stack.back().second++;
// 如果达到3个或以上
if (stack.back().second >= 3) {
stack.pop_back();
changed = true;
}
}
}
// 重建字符串
for (const auto& p : stack) {
result.append(p.second, p.first);
}
// 更新字符串
if (changed) {
s = result;
}
}
return s;
}
};
int main() {
string s;
cin >> s;
Solution solution;
cout << solution.removeRepeated(s) << endl;
return 0;
}
public class Main {
static class CharCount {
char ch;
int count;
CharCount(char ch, int count) {
this.ch = ch;
this.count = count;
}
}
static class Solution {
public String removeRepeated(String s) {
boolean changed = true;
while (changed) {
changed = false;
StringBuilder result = new StringBuilder();
ArrayList<CharCount> stack = new ArrayList<>();
// 处理每个字符
for (char c : s.toCharArray()) {
if (stack.isEmpty() || stack.get(stack.size()-1).ch != c) {
// 新字符,压入栈
stack.add(new CharCount(c, 1));
} else {
// 相同字符,增加计数
CharCount last = stack.get(stack.size()-1);
last.count++;
// 如果达到3个或以上
if (last.count >= 3) {
stack.remove(stack.size()-1);
changed = true;
}
}
}
// 重建字符串
for (CharCount cc : stack) {
// 使用循环替代repeat方法
for (int i = 0; i < cc.count; i++) {
result.append(cc.ch);
}
}
// 更新字符串
if (changed) {
s = result.toString();
}
}
return s;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
Solution solution = new Solution();
System.out.println(solution.removeRepeated(s));
sc.close();
}
}
class Solution:
def remove_repeated(self, s: str) -> str:
changed = True
while changed:
changed = False
stack = [] # [(char, count)]
# 处理每个字符
for c in s:
if not stack or stack[-1][0] != c:
# 新字符,压入栈
stack.append([c, 1])
else:
# 相同字符,增加计数
stack[-1][1] += 1
# 如果达到3个或以上
if stack[-1][1] >= 3:
stack.pop()
changed = True
# 重建字符串
result = ''.join(c * count for c, count in stack)
# 更新字符串
if changed:
s = result
return s
def main():
s = input().strip()
solution = Solution()
print(solution.remove_repeated(s))
if __name__ == "__main__":
main()
算法及复杂度
- 算法:栈 + 模拟
- 时间复杂度:
,其中
是字符串长度(最坏情况下需要多次扫描)
- 空间复杂度:
,需要栈来存储字符