把string当栈用,扫一遍就可以了,时间复杂度O(n)
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
string st;
for (int i = 0; i < n; ++i) {
if (st.empty() || st.back() != s[i]) {
st.push_back(s[i]);
} else {
st.pop_back();
}
}
if (st.size() == 0) cout << 0;
else cout << st;
return 0;
}