본문 바로가기

알고리즘(백준 등) 공부

SWEA 25330. 거리 문자열

0부터 9까지의 숫자로 이루어진 길이 10 이하의 문자열에서 다음의 조건을 만족하면 yes, 아니면 no를 출력한다.

  • 0부터 9까지의 숫자가 등장하거나 2번만 등장한다.
  • 숫자 d 사이의 숫자 갯수는 d개 이다.

 

각 숫자들이 0개 혹은 두 개만 등장하므로 먼저 문자열의 길이가 짝수인지 부터 확인한다.

if(str.length() % 2 != 0) {
    sb.append("no").append('\n');
    continue;
}

 

 

이후, 처음부터 끝까지 순회하면서 각 숫자가 정확히 2번 발견되는지, 숫자 d 사이의 갯수가 d개 인지 확인한다. 숫자 사이의 갯수 확인은 처음 발견된 숫자의 위치 + d + 1 의 숫자가 d여야 d 사이에 d개 있다는 것이며 해당 위치의 숫자가 d인지 확인한다.

int[] board = new int[10];
for(int i=0; i<str.length(); i++) {
    int number = Integer.parseInt(str.substring(i, i+1));
    if(board[number] == 1) {
        board[number] = 2;
        continue;
    }
    if(board[number] >= 2) {
        sb.append("no").append('\n');
        continue outer;
    }
    if(i + number + 1 >= str.length()) {
        sb.append("no").append('\n');
        continue outer;
    }
    if(Integer.parseInt(str.substring(i + number + 1, i + number + 2)) == number) {
        board[number] = 1;
    } else {
        sb.append("no").append('\n');
        continue outer;
    }
}
sb.append("yes").append('\n');

 

 

결과 코드는 다음과 같다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();
        outer: while(T-- > 0) {
            String str = br.readLine();
            if(str.length() % 2 != 0) {
                sb.append("no").append('\n');
                continue;
            }
            int[] board = new int[10];
            for(int i=0; i<str.length(); i++) {
                int number = Integer.parseInt(str.substring(i, i+1));
                if(board[number] == 1) {
                    board[number] = 2;
                    continue;
                }
                if(board[number] >= 2) {
                    sb.append("no").append('\n');
                    continue outer;
                }
                if(i + number + 1 >= str.length()) {
                    sb.append("no").append('\n');
                    continue outer;
                }
                if(Integer.parseInt(str.substring(i + number + 1, i + number + 2)) == number) {
                    board[number] = 1;
                } else {
                    sb.append("no").append('\n');
                    continue outer;
                }
            }
            sb.append("yes").append('\n');
        }
        br.close();
        System.out.print(sb);
    }
}

'알고리즘(백준 등) 공부' 카테고리의 다른 글

SWEA 24524. 레벨업  (0) 2026.04.14
SWEA 24696. 직육면체 자르기  (0) 2026.04.13
SWEA 25695. 세 정수  (0) 2026.04.09
SWEA 25837. 합과 곱  (0) 2026.04.08
SWEA 25838. 여우 줄이기  (0) 2026.04.07