📅  最后修改于: 2023-12-03 15:28:22.651000             🧑  作者: Mango
在编程过程中,有时候会出现相邻重复的元素,需要将其删除。这个问题可以通过递归算法来解决。
本文将通过C++语言来实现递归删除所有相邻重复的元素。
void removeDuplicates(string &s) {
...
}
void removeDuplicates(string &s) {
int i = 0;
...
}
void removeDuplicates(string &s) {
int i = 0;
if(s.size() < 2) {
return;
}
...
}
void removeDuplicates(string &s) {
int i = 0, prev = -1, curr = 0;
if(s.size() < 2) {
return;
}
while(curr < s.size()) {
if(curr > 0 && s[curr] == s[prev]) {
curr++;
} else {
if(curr - prev > 1) {
removeDuplicates(s.substr(prev + 1, curr - prev - 1));
}
prev = curr;
curr++;
}
}
...
}
void removeDuplicates(string &s) {
int i = 0, prev = -1, curr = 0;
if(s.size() < 2) {
return;
}
while(curr < s.size()) {
if(curr > 0 && s[curr] == s[prev]) {
curr++;
} else {
if(curr - prev > 1) {
string str = s.substr(prev + 1, curr - prev - 1);
removeDuplicates(str);
s.replace(prev + 1, curr - prev - 1, str);
curr = prev + 1;
} else {
prev = curr;
curr++;
}
}
}
}
#include <iostream>
#include <string>
using namespace std;
void removeDuplicates(string &s) {
int i = 0, prev = -1, curr = 0;
if(s.size() < 2) {
return;
}
while(curr < s.size()) {
if(curr > 0 && s[curr] == s[prev]) {
curr++;
} else {
if(curr - prev > 1) {
string str = s.substr(prev + 1, curr - prev - 1);
removeDuplicates(str);
s.replace(prev + 1, curr - prev - 1, str);
curr = prev + 1;
} else {
prev = curr;
curr++;
}
}
}
}
int main() {
string s;
cout << "请输入字符串: ";
getline(cin, s);
removeDuplicates(s);
cout << "删除相邻重复字符后: " << s << endl;
return 0;
}
以上是递归删除所有相邻重复项的 C++ 程序。