Official

B - Prefix and Suffix Editorial by en_translator


This problem features prefix and suffix. The concept of prefix and suffix is often seen in other problems, so do learn it if you have never heard of.

As defined in the problem statement, a prefix and a suffix are strings described as follows.

  • We have strings \(S\) and \(T\). Let \(N\) be the length of \(S\). Then,
    • \(S\) is said to be a prefix of \(T\) if the first \(N\) characters of \(T\) coincide with \(S\).
    • \(S\) is said to be a suffix of \(T\) if the first \(N\) characters of \(T\) coincide with \(S\).

If one can determine if \(S\) is a prefix/suffix of \(T\), then one can solve the problem by printing the corresponding number.

The decision problem can be solved by using a for loop properly. For example, regarding the prefix, one can inspect

  • whether the \(1\)-st characters of \(S\) and \(T\) coincides;
  • whether the \(2\)-nd characters of \(S\) and \(T\) coincides;
  • \(\vdots\)
  • whether the \(N\)-th characters of \(S\) and \(T\) coincides;

if all of them are true, then \(S\) is a prefix of \(T\); otherwise, it is not. (Same goes to suffix too.)

A sample code in C++ follows.

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

int main() {
  int N, M;
  string S, T;
  cin >> N >> M >> S >> T;

  int is_prefix = true;
  for (int i = 0; i < N; i++) {
    if (S[i] != T[i]) is_prefix = false;
  }
  int is_suffix = true;
  for (int i = 0; i < N; i++) {
    if (S[i] != T[M - N + i]) is_suffix = false;
  }

  if (is_prefix) {
    cout << (is_suffix ? 0 : 1) << endl;
  } else {
    cout << (is_suffix ? 2 : 3) << endl;
  }
}

posted:
last update: