작성일 :

문제 링크

1013번 - Contact

설명

주어진 0과 1로 이루어진 문자열이 특정 패턴을 만족하는지 판별하는 문제입니다. 패턴은 1 다음에 0이 한 개 이상, 그 다음 1이 한 개 이상인 경우와 01인 경우 중 하나가 반복되는 형태입니다.


접근법

정규 표현식을 사용하면 간단하게 해결할 수 있습니다. 문자열 전체가 패턴과 정확히 일치해야 하므로 전체 매치를 사용합니다. 문자열 길이가 최대 200이므로 정규식 엔진의 성능으로 충분합니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    var t = int.Parse(Console.ReadLine()!);
    var rx = new Regex("^(100+1+|01)+$");
    for (var i = 0; i < t; i++) {
      var s = Console.ReadLine()!;
      Console.WriteLine(rx.IsMatch(s) ? "YES" : "NO");
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

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

  int t; cin >> t;
  const regex re("(100+1+|01)+");
  while (t--) {
    string s; cin >> s;
    cout << (regex_match(s, re) ? "YES" : "NO") << "\n";
  }

  return 0;
}