String Task (118A) asks you to apply three small transformations to every character of a string. It is a good exercise in reading a statement carefully, because it contains one detail that catches a lot of people: in this problem, Y counts as a vowel.
The problem in short
You are given one string of uppercase and lowercase Latin letters, up to 100 characters long. Produce a new string by:
- deleting every vowel, where the vowels are A, O, Y, E, U, I;
- putting a dot
.before every remaining consonant; - replacing every uppercase consonant with its lowercase version.
Full statement: Codeforces 118A – String Task.
Approach
We never need to build the result in memory. We can walk through the input once and print as we go:
- Convert the current character to lowercase with
tolower. This handles step 3 and also means we only need to compare against lowercase vowels. - If it is a vowel, skip it.
- Otherwise, print a dot followed by the character.
To test for a vowel, I use strchr("aoyeui", c), which returns a non-NULL pointer if c appears in that string. It reads more clearly than a chain of six comparisons.
Example
Codeforces
Lowercased, the letters are c, o, d, e, f, o, r, c, e, s. Removing o and e leaves c, d, f, r, c, s, and adding dots gives .c.d.f.r.c.s.
Another sample is aBAcAba. The consonants are B, c, b. Lowercased and dotted: .b.c.b.
Solution in C
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_vowel(char c) {
return strchr("aoyeui", c) != NULL;
}
int main(void) {
char s[105];
scanf("%s", s);
for (int i = 0; s[i] != '\0'; i++) {
char c = tolower((unsigned char)s[i]);
if (!is_vowel(c))
printf(".%c", c);
}
printf("\n");
return 0;
}
The cast to unsigned char in tolower is a good habit. Passing a negative char to the ctype.h functions is undefined behavior. It cannot happen with plain Latin letters, but it is free insurance.
Complexity
One pass over the string, and each vowel check scans at most 6 characters: O(n) time, O(n) memory for the input buffer.
Common mistakes
- Forgetting Y. In English we usually say there are five vowels, but this problem lists six.
- Checking vowels before lowercasing, so uppercase vowels like
Aslip through as consonants. - Printing the dot after the letter instead of before it.
Practice next
Try 112A Petya and Strings for another case-insensitive string problem, or 71A Way Too Long Words.
No comments:
Post a Comment