본문 바로가기
알고리즘 문제풀이 입문: 코딩테스트 대비/섹션 1. String(문자열)

가장 짧은 문자 거리

by _비니_ 2024. 4. 2.

 

문제 이해

 

주어진 문자열 s를 돌며 특정 문자 t와의 최소 거리를 출력하는 문제이다.

이 문제의 포인트는 여러 번의 문자 t를 마주할 수 있는데, 더 짧은 거리를 출력해야하는 것에 있다.

 

 

문제 해결

 

먼저 특정 문자 t를 구분하기 위해 split을 사용해 공백을 기준으로 배열에 넣어준다.

Scanner in = new Scanner(System.in);
String input = in.nextLine();
String[] words = input.split(" ");

 

words 배열의 0번째 인덱스가 문자열 s, 1번째 인덱스의 0번째 추출 문자가 특정 문자 t를 의미하므로 각각을 변수에 넣어준다.

String str = words[0];
char standardCh = words[1].charAt(0);

 

특정 문자들의 인덱스들을 저장하기 위해 문자열 s를 돌며 특정문자와 같은 문자를 발견하면 그 곳의 인덱스를 리스트에 넣어준다.

ArrayList<Integer> standardIndexs = new ArrayList<>();

for (int i = 0; i < str.length(); i++) {
    if(str.charAt(i) == standardCh)
        standardIndexs.add(i); //기준 문자들의 인덱스들 저장
}

 

 

특정 문자들이 저장된 리스트에서 값을 하나씩 꺼내 거리를 계산하며 더 작은 값을 갱신하며 최소 거리를 출력하는 for문을 문자열 s의 길이만큼 반복해준다.

for (int i = 0; i < str.length(); i++) {
    int minDistance = 10000;

    for(int standardIndex : standardIndexs) {
        int distance = Math.abs(i-standardIndex); //i번째 인덱스 - 추출 문자 인덱스의 절대값
        minDistance = Math.min(minDistance, distance); //더 작은 거리를 저장
    }
    System.out.print(minDistance + " ");
}

 

 

최종 코드

 

import java.util.ArrayList;
import java.util.Scanner;

public class P10_가장짧은문자거리 {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        String[] words = input.split(" ");

        String str = words[0];
        char standardCh = words[1].charAt(0);

        ArrayList<Integer> standardIndexs = new ArrayList<>();

        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == standardCh)
                standardIndexs.add(i); //기준 문자들의 인덱스들 저장
        }

        for (int i = 0; i < str.length(); i++) {
            int minDistance = 10000;

            for(int standardIndex : standardIndexs) {
                int distance = Math.abs(i-standardIndex); //i번째 인덱스 - 추출 문자 인덱스의 절대값
                minDistance = Math.min(minDistance, distance); //더 작은 거리를 저장
            }
            System.out.print(minDistance + " ");
        }

    }
}
반응형