A - 旅の記録 / Travel Records Editorial by admin
gpt-6-astra-mediumOverview
We need to find the number of uppercase English letters contained in a string \(S\). In the provided code, the answer is obtained by counting the number of lowercase English letters and subtracting it from the total length of the string \(N\).
Analysis
Every character in \(S\) is either an uppercase English letter or a lowercase English letter. Therefore, the following relationship holds:
\(\text{number of uppercase letters} = N - \text{number of lowercase letters}\)
Using this relationship, we can find the answer by examining the characters of the string from beginning to end and counting the number of lowercase English letters.
For example, when \(N = 5\) and \(S =\) AbCdE, there are \(2\) lowercase English letters: b and d. Therefore, the number of uppercase English letters is \(5 - 2 = 3\).
Note that the naive approach of directly counting uppercase English letters is also correct. Since \(N\) is small (\(N \leq 100\)), inspecting every character once is sufficiently fast, and no special optimization is required.
Also, what we need to find is the number of occurrences, not the number of distinct characters. If the same uppercase English letter appears multiple times, it must be counted each time.
Algorithm
- Read \(N\) and \(S\).
- Initialize a variable
lowerrepresenting the number of lowercase English letters to \(0\). - Examine each character of \(S\) in order:
- If the character is between
'a'and'z'inclusive, it is a lowercase English letter, so incrementlowerby \(1\).
- If the character is between
- Output \(N - \text{lower}\).
After examining all characters, lower will hold the total number of lowercase English letters. Since all remaining characters are uppercase English letters, \(N - \text{lower}\) is the desired answer.
Complexity
- Time complexity: \(O(N)\)
Each character of the string is inspected once. - Space complexity: \(O(N)\)
Required to store the input string \(S\). The additional working space, excluding storing the string, is \(O(1)\).
Implementation Notes
Since string indices in C++ start from \(0\), iterate over the range from
i = 0toi < n.Checking whether a character is a lowercase English letter can be written as
s[i] >= 'a' && s[i] <= 'z'.If there are no uppercase English letters, \(0\) will be output, and if all characters are uppercase, \(N\) will be output; this logic handles both cases correctly as-is.
Source Code
// 問題文から独立に実装: 小文字を数えて全体から引く
#include <iostream>
#include <string>
int main() {
int n; std::string s; std::cin >> n >> s;
int lower = 0;
for (int i = 0; i < n; ++i) if (s[i] >= 'a' && s[i] <= 'z') lower++;
std::cout << n - lower << std::endl;
}
This editorial was generated by gpt-6-astra-medium.