公式

A - I'm a teapot 解説 by en_translator


For beginners

First, if the length of \(S\) is less than 3, the answer is No.
Otherwise, the answer is Yes if the following three conditions are all satisfied, and No otherwise:

  • The \((N-2)\)-th character of \(S\) is t.
  • The \((N-1)\)-th character of \(S\) is e.
  • The \(N\)-th character of \(S\) is a.

We can inspect those characters one by one.
Notice that if you try to access the \((N-2)\)-th character when the length of \(S\) is less than \(3\), some languages or situations may produce a runtime error called out-of-bounds array access. (To put informally, the index becomes negative, which causes an attempt to inspect outside the string, leading to an error.) Thus, make sure to check the string length before accessing to the string to avoid out-of-bounds array access.

As an alternative solution, one can also extract the last three characters using substr function in C++ or the slice feature in Python, and compare it with tea.

  • Sample code (C++)
#include <iostream>
#include <string>
using namespace std;

int main() {
  int N;
  string S;
  cin >> N >> S;
  if (N < 3) {
    cout << "No\n";
  } else {
    if (S[N - 3] == 't' and S[N - 2] == 'e' and S[N - 1] == 'a') {
      cout << "Yes\n";
    } else {
      cout << "No\n";
    }
  }
}

投稿日時:
最終更新: