AtCoder Beginner Contest 167 A I will explain the problem "Registration".
Problem URL: https://atcoder.jp/contests/abc167/tasks/abc167_a
Given the strings $ S $, $ T $. Determine if $ T $ is a string with one character added to the end of $ S $.
Yes if $ T $ meets the conditions
If the conditions are not met, output No.
・ $ S and T $ are lowercase letters
・
String
In Python3, you can use T [i: j + 1] to get the  slice </ b> from the $ i $ character to the $ j $ character of $ T $.
 (note that it is 0-index here) </ font>
On computers, numeric counters start at 0 instead of 1. So, the strings we process are counted from the first character for us, but the 0th character for computers. </ b> The method of counting computer-like arrays (including character strings) is called 0-index </ b>. On the other hand, the way we usually count arrays is called 1-index </ b>. Keep in mind that it will be used frequently in the explanations in the future.
Let's get back to the main subject.
In C ++, you can use T.substr (i, j) to get  slices </ b> of $ j $ characters from the $ i $ th of $ T $. (i is 0-index)
In Java, you can get  slices </ b> from $ i $ th to $ j $ th of $ T $ with T.substring (i, j + 1). (i, j are 0-index)
You can use these functions to get a slice of $ T $ and determine if it is the same as $ S $.
Below are examples of solutions in Python3, C ++, and Java.
{ABC167A.py}
S = input()
T = input()
if T[0:len(S)] == S:
  print("Yes")
else:
  print("No")
{ABC167A.cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
  string S,T;
  cin >> S >> T;
  string Judge = T.substr(0,S.size());
  if (Judge == S){
    cout << "Yes" << endl;
  }else{
    cout << "No" << endl;
  }
}
{ABC167A.java}
import java.util.Scanner;
public class Main{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    String S = scan.nextLine();
    String T = scan.nextLine();
    String judge = T.substring(0,S.length());
    if (judge == S){
      System.out.println("Yes");
    }else{
      System.out.println("No");
    }
  }
}
In fact, when I run this code, I get WA </ font>. Do you know why (if you know)?
If you want to know the reason, please check it out.
The correct code is as follows.
{ABC167A_AC.java}
import java.util.Scanner;
public class Main{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    String S = scan.next();
    String T = scan.next();
    String judge = T.substring(0,S.length());
    if (S.equals(judge)){
      System.out.println("Yes");
    }else{
      System.out.println("No");
    }
  }
}
Recommended Posts