公式

A - ab 解説 by en_translator


For beginners

This problem asks to determine if there is an integer \(i\) such that:

  • \(1 \leq i \leq N - 1\);
  • the \(i\)-th and \((i+1)\)-th characters of \(S\) are a and b or b and a, respectively.

Therefore, it is sufficient to receive \(S\) from the input, use a loop structure like a for statement to scan \(i\) for each of \(1, 2, \dots, N-1\), and check if any \(i\) satisfies the condition.

The following is sample code in C++. (When reading the sample code, note that the index \(i\) differs by \(1\), because the first character of a string type is treated as S[0].)

#include <iostream>
#include <string>
using namespace std;

int main() {
  int N;
  string S;
  cin >> N >> S;
  bool yes = false;
  for (int i = 0; i < N - 1; i++) {
    if (S[i] == 'a' and S[i + 1] == 'b') yes = true;
    if (S[i] == 'b' and S[i + 1] == 'a') yes = true;
  }
  cout << (yes ? "Yes" : "No") << endl;
}

投稿日時:
最終更新: