끄적끄적 코딩
article thumbnail
Published 2023. 7. 3. 22:18
[Java] 백준 1013번 Contact 알고리즘

문자열 문제입니다.

(100+1+ | 01)+ 의 규칙을 가졌는지 확인하면 됩니다.

위의 규칙을 가졌을 경우 YES
가지지 않았을 경우 NO를 출력합니다.

단일 숫자는 해당 숫자가 존재하는지를 나타냅니다.
10 => 10이라는 숫자가 있어야함
1+ => 1이라는 숫자가 N개 존재
10+1 => 1과 1사이에 0이 N개 존재함
(1+ | 01)+ (1이 N개 있거나 0다음 1이 M개 있음)이 P개 있음

위와 같이 규칙이 존재합니다.
그렇다면 (100+1+ | 01)+ 의 경우에는
(100+1+ 또는 01+)가 N개 존재하는 경우
100+1+는 1 0 (0이 N개) (1이  M개) 있는 경우
01는 01이 있는 경우

if문을 잘 설정해서 위의 경우에 해당하는지 찾으면 됩니다.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
  static int n;
  static boolean chk;
  static String s;

  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

    int n = Integer.parseInt(br.readLine());

    for (int i = 0; i < n; ++i) {
      s = br.readLine();
      chk = dfs(0, 0, 0);

      if (chk) {
        bw.write("YES\n");
      } else {
        bw.write("NO\n");
      }
    }
    bw.close();
  }

  public static boolean dfs(int index, int state, int stateIndex) {
    if (index == s.length()) {
      if (stateIndex == 0) {
        return true;
      } else {
        return false;
      }
    }

    if (stateIndex == 0) {
      if (s.charAt(index) == '0') {
        return dfs(index, 0, 1);
      } else {
        return dfs(index, 1, 1);
      }
    }

    if (stateIndex == 1) {
      return dfs(index + 1, state, stateIndex + 1);
    }

    if (stateIndex == 2) {
      if (s.charAt(index) - 48 != state) {
        if (state == 0) {
          return dfs(index + 1, 0, 0);
        } else {
          return dfs(index + 1, state, stateIndex + 1);
        }
      } else {
        return false;
      }
    }

    if (stateIndex == 3) {
      if (s.charAt(index) == '0') {
        return dfs(index + 1, state, stateIndex + 1);
      } else {
        return false;
      }
    }

    if (stateIndex == 4) {
      if (s.charAt(index) == '0') {
        return dfs(index + 1, state, stateIndex);
      } else {
        return dfs(index + 1, 0, 0) || dfs(index + 1, state, stateIndex + 1);
      }
    }

    if (stateIndex == 5) {
      if (s.charAt(index) == '1') {
        return dfs(index + 1, 0, 0) || dfs(index + 1, state, stateIndex);
      } else {
        return false;
      }
    }

    return true;
  }
}

'알고리즘' 카테고리의 다른 글

[Java] 백준 2580번 스도쿠  (0) 2023.07.05
[Java] 백준 9663번 N-Queen  (0) 2023.07.04
[Java] 백준 1253번 좋다  (0) 2023.07.03
[Java] 백준 2310번 어드벤처 게임  (0) 2023.07.01
[Java] 백준 1043번 거짓말  (0) 2023.06.30

검색 태그