公式

A - First ABC 2 解説 by en_translator


For beginners

This problem asks to handle strings and loop structures like for statements.

According to the problem statement, it asks to find the minimum integer \(n\) (or \(-1\) if none of them does) such that:

  • \(1 \leq n \leq N - 2\)
  • the \(n\)-th character of \(S\) is A;
  • the \((n+1)\)-th character of \(S\) is B;
  • the \((n+2)\)-th character of \(S\) is C.

Therefore, it is sufficient to scan \(n\) for each \(1, 2, \dots, N-2\) in a for statement, and determine for each \(n\) if it satisfies the condition. To obtain the \(n\)-th character of \(S\), most programming language provides array subscript operator S[n].

Sample codes in C++ and Python follow. (When reading a sample code, note that the index \(n\) differs by \(1\), since the initial character of a string is considered as S[0].)

  • C++
#include <iostream>
#include <string>
using namespace std;

int main() {
  int N;
  string S;
  cin >> N >> S;
  int ans = -1;
  for (int i = 0; i < N - 2; i++) {
    if (S[i] == 'A' and S[i + 1] == 'B' and S[i + 2] == 'C') {
      ans = i + 1;
      break;
    }
  }
  cout << ans << endl;
}
  • Python
N = int(input())
S = input()
ans = -1
for i in range(N-2):
    if S[i] == 'A' and S[i+1] == 'B' and S[i+2] == 'C':
        ans = i + 1
        break
print(ans)

投稿日時:
最終更新: