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が与えられる。aとbが隣接して現れる場所があるか判定しろ。

解法と実装

for文を使って、順番に文字列を確認します。
i番目とi+1番目について判断するので、rangeはN-1までになります。ここでNとすると、(最初の文字を0番目とした時の)N-1+1すなわちN番目を参照することになるので、範囲外参照エラーが発生します。

N = int(input()) # 文字数の受け取り
S = input() # 文字列の受け取り
ans = False # abを含むかどうかの判定をフラグで管理

for i in range(N-1): # i+1番目を確認するので、rangeはN-1
  if S[i] == 'a' and S[i+1] == 'b': # abがあるか判定
    ans = True
  if S[i] == 'b' and S[i+1] == 'a': # ba
    ans = True

if ans: # フラグで答えを確認
  print("Yes")
else:
  print("No")

aとbの隣接を判定するということは、Sの中に連続する部分文字列としてabまたはbaが含まれるかどうかという問題になります。すなわち、Sの一部を見たときに、abまたはbaがあるかどうか判定すれば良いです。
aとbの順序は問わないので、abだけではなくbaについても判定が必要なので注意してください。

N = int(input())
S = input()
if 'ab' in S or 'ba' in S: # Sの中に'ab'または'ba'という部分文字列があるかどうか
  print("Yes")
else:
  print("No")
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?