Official
D - Uppercase and Lowercase Editorial by en_translator
This problem asks to process strings. If you could not solve this problem, review how to treat strings.
This problem can be solved by the following steps.
- Count the occurrences of lowercase letters in \(S\), and that of uppercase ones, and compare them.
- if the number of lowercase letters is fewer than that of uppercase ones, make all uppercase letters in \(S\) lowercase.
- if the number of lowercase letters is more than that of uppercase ones, make all lowercase letters in \(S\) uppercase.
Most programming languages come with functions handling lowercase and uppercase letters. For example, C++ provides the following functions:
islower(c): function that determines ifcis a lowercase letter.isupper(c): function that determines ifcis an uppercase letter.tolower(c): function that convertscto lowercase letters.toupper(c): function that convertscto uppercase letters.
One can appropriately use these functions to implement the procedure above. The complexity is \(\mathrm{O}(|S|)\), which is fast enough.
- Sample code (C++)
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main() {
string S;
cin >> S;
int lower = 0, upper = 0;
for (auto& c : S) {
(islower(c) ? lower : upper)++;
}
if (lower < upper) {
for (auto& c : S) {
if (islower(c)) c = toupper(c);
}
} else {
for (auto& c : S) {
if (isupper(c)) c = tolower(c);
}
}
cout << S << "\n";
}
posted:
last update: