Remove Hollow Letters
National Olympiad — Regional round (2012 season)
Submission name: lazy.cpp
Problem summary
Delete all spaces and all letters in the set a,b,d,e,g,o,p,q from a text, retaining the other letters in their original order.
Input
n, then one line of n lowercase Latin letters and spaces; no leading or trailing spaces.
Output
The remaining text, without spaces.
Constraints
1 ≤ n ≤ 100,000.
Worked example
An independently prepared example for this explanation.
Input
17 a sample sentence
Output
smlsntnc
Solution analysis
- The decision to keep a character depends only on that character. Store the eight forbidden letters in a small string.
- Read the whole text line with getline after consuming the newline following n. Print a character only when it is neither a space nor forbidden.
- In a sample sentence, removing a,p,e and all spaces leaves smlsntnc. The surviving letters keep their original order.
Why it works
Each character is printed exactly when it is allowed. The left-to-right scan preserves order, so its output is precisely the text after the required deletions.
Watch out. Formatted word input alone loses the original spaces, though filtering tokens would also work. An empty result should still end with a newline.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main() {
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string text;
getline(cin, text);
const string forbidden = "abdegopq";
// Print survivors immediately to preserve their original order.
for (char letter : text) {
if (letter != ' ' && forbidden.find(letter) == string::npos) {
cout << letter;
}
}
cout << '\n';
}