작성일 :

문제 링크

16446번 - Enigma

설명

암호문과 단어 crib이 주어집니다. Enigma는 동일 문자를 동일 위치로 매핑하지 않으므로, crib을 암호문에 겹쳐 놓았을 때 어느 자리든 같은 문자가 나오면 그 위치는 불가능합니다.

가능한 시작 위치의 개수를 세는 문제입니다.


접근법

먼저, 모든 시작 위치에 대해 crib의 각 문자와 암호문의 해당 위치 문자를 비교합니다.

다음으로, 같은 문자가 하나라도 나오면 그 위치는 불가능합니다. 끝까지 충돌이 없으면 개수를 증가시킵니다.

길이가 최대 10000이므로 단순 이중 반복으로도 충분합니다.



Code

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
26
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var s = Console.ReadLine()!;
      var crib = Console.ReadLine()!;
      var n = s.Length;
      var m = crib.Length;
      var ans = 0;

      for (var i = 0; i + m <= n; i++) {
        var ok = true;
        for (var j = 0; j < m; j++) {
          if (s[i + j] == crib[j]) {
            ok = false;
            break;
          }
        }
        if (ok) ans++;
      }

      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
26
#include <bits/stdc++.h>
using namespace std;

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

  string s, crib; cin >> s >> crib;
  int n = s.size(), m = crib.size();
  int ans = 0;

  for (int i = 0; i + m <= n; i++) {
    bool ok = true;
    for (int j = 0; j < m; j++) {
      if (s[i + j] == crib[j]) {
        ok = false;
        break;
      }
    }
    if (ok) ans++;
  }

  cout << ans << "\n";

  return 0;
}