解題思路
每個字母各自維護出現次數,讀到時先加一。
新的次數為奇數就保留,偶數就略過。由於次數包括目前位置,這正好保留每種字母的第1、3、5…次出現。
時間 O(|S|),輸入及輸出 O(|S|),頻率表 O(26)。
Step-by-step animation
教學例子:abacaba,前兩字a、b各首次,保留ab。
步驟 1 / 3
步驟 1
abacaba,前兩字a、b各首次,保留ab。
a
b
- 狀態
- ab
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s, out;
cin >> s;
int cnt[26] = {};
for (char c : s)
if (++cnt[c - 'a'] % 2)
out += c;
cout << out << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。