A - A Substring 解説 by en_translator
For beginners
Roughly, there are two approaches.
- Print the characters that are not removed in order.
- Construct a string to be printed, and print it.
We describe each approach.
1. Print the characters that are not removed in order
The characters removed from \(S\) are the \(1\)-st, \(2\)-nd, \(\ldots,A\)-th, \(N-B+1\)-th \(,N-B+2\)-th, \(\ldots\), and \(N\)-th characters.
In other words, the characters that are not removed are the \(A+1\)-th through \(N-B\)-th characters.
The problem can be solved by printing these characters in order. If the printing function of your language emits a space or a newline at the end by default, be careful not to print an excessive delimiter when printing the characters one by one.
The following is sample code.
Sample code in C++
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, A, B;
cin >> N >> A >> B;
string S;
cin >> S;
// Remove the first A characters and remove B characters
// = in 0-based indexing, A-th and later characters, but before the B-th, remain.
int start = A;
int end = N - B;
// Print the characters not removed
for (int i = start; i < end; ++i) {
cout << S[i];
}
cout << endl;
return 0;
}
Python での実装例
N, A, B = map(int, input().split())
S = input()
# Remove the first A characters and remove B characters
# = in 0-based indexing, A-th and later characters, but before the B-th, remain.
start = A
end = N - B
# Print the characters not removed
for i in range(start, end):
print(S[i], end='')
2. Construct a string to be printed and print it
In some languages, there is a method to extract a consecutive portion of a string to obtain a new string.
For example, in C++ this can be done by calling a member function substr
on a string
-type variable; in Python, by accessing a str
-type variable as a slice.
The following is sample code.
Sample code in C++
The substr
function accepts the position of the first character and the number of characters to extract, to obtain a consecutive portion of a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, A, B;
cin >> N >> A >> B;
string S;
cin >> S;
// (in 0-based indexing) from the A-th character, extract a total of (N - A - B) characters
cout << S.substr(A, N - A - B) << endl;
return 0;
}
Sample code in Python
In Python, when you want to remove the last \(B\) characters of a string using the slice notation, if you apply [:-B]
the behavior is not what you want when \(B=0\), so you need to tweak the method.
For example, one can append one more character to \(S\) so that \(B\) becomes positive, or access by \(N-B\) instead of \(-B\).
N, A, B = map(int, input().split())
S = input()
S += 'a' # to access with [:-B], append one excessive character
B += 1 # increment B as well
print(S[A:-B])
投稿日時:
最終更新: