작성일 :

문제 링크

32401번 - ANA는 회문이야

설명

문자열 S의 부분 문자열 중 유사 ANA 문자열의 개수를 구하는 문제입니다.


접근법

시작 문자가 A인 위치에서 끝 위치를 늘려가며 내부에 A가 없는지, N이 정확히 한 개인지 확인합니다.
끝 문자도 A이고 길이가 3 이상이면 조건을 만족하므로 개수를 증가시킵니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;

class Program {
  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var s = Console.ReadLine()!;
    var ans = 0;

    for (var i = 0; i < n; i++) {
      if (s[i] != 'A') continue;
      var cntA = 0;
      var cntN = 0;
      for (var j = i + 1; j < n; j++) {
        if (j >= i + 2 && s[j] == 'A' && cntA == 0 && cntN == 1) ans++;
        if (s[j] == 'A') cntA++;
        if (s[j] == 'N') cntN++;
      }
    }

    Console.WriteLine(ans);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  string s; cin >> s;
  int ans = 0;

  for (int i = 0; i < n; i++) {
    if (s[i] != 'A') continue;
    int cntA = 0, cntN = 0;
    for (int j = i + 1; j < n; j++) {
      if (j >= i + 2 && s[j] == 'A' && cntA == 0 && cntN == 1) ans++;
      if (s[j] == 'A') cntA++;
      if (s[j] == 'N') cntN++;
    }
  }

  cout << ans << "\n";

  return 0;
}