0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

問題概要

N文字の文字列Sが与えられ、Sが"tea"で終わる文字列かどうか判定する。

解法と実装

数字と文字列を受け取って、文字列を後ろからif文で判定します。

N = int(input()) # 文字列の長さNをint型として受け取る
S = input() # 文字列Sを受け取る(指定していないのでstring型)

if N < 3:
  print("No") # 3文字未満の文字列で、"tea"で終わる文字列はない
else:
  if S[-3] == 't' and S[-2] == 'e' and S[-1] == 'a': # 後ろから3、2、1文字目がそれぞれt、e、aなのか確認する
    print("Yes")
  else:
    print("No")

部分文字列としてまとめて判定することもできます。

N = int(input()) # 文字列の長さNをint型として受け取る
S = input() # 文字列Sを受け取る(指定していないのでstring型)

if N < 3:
  print("No") # 3文字未満の文字列で、"tea"で終わる文字列はない
else:
  if S[-3:] == "tea": # 後ろから3文字目以降の部分文字列が"tea"となっているか判定する
    print("Yes")
  else:
    print("No")

備考

文字列が3文字未満の時にS[-3]と書くと、文字列の後ろから3番目の文字は存在しないので、範囲外参照エラーが起きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?