백준 3048번 개미

이상민·2023년 10월 30일
0

알고리즘

목록 보기
83/128
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Ant {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N1 = Integer.parseInt(st.nextToken());
        int N2 = Integer.parseInt(st.nextToken());
        HashSet<Character> set1 = new HashSet<>();
        HashSet<Character> set2 = new HashSet<>();
        char[] chars = new char[N1+N2];
        String str = br.readLine();
        for (int i = 0; i < N1; i++) {
            chars[i] = str.charAt(N1-1-i);
            set1.add(chars[i]);
        }
        str = br.readLine();
        for (int i = 0; i < N2; i++) {
            chars[N1+i] = str.charAt(i);
            set2.add(chars[N1+i]);
        }
        int T = Integer.parseInt(br.readLine());
        for (int i = 0; i < T; i++) {
            List<int[]> list = new ArrayList<>();
            for (int j = N1+N2-2; j >=0 ; j--) {
                if(set1.contains(chars[j])&&set2.contains(chars[j+1])){
                    list.add(new int[]{j,j+1});
                }
            }
            for (int j = 0; j < list.size(); j++) {
                char temp = chars[list.get(j)[0]];
                chars[list.get(j)[0]] = chars[list.get(j)[1]];
                chars[list.get(j)[1]] = temp;
            }
        }
        StringBuilder sb = new StringBuilder();
        for(char c : chars){
            sb.append(c);
        }
        System.out.println(sb);

    }
}

풀이방법

  1. 입력받을때, chars에 문자열을 전부 입력받고,
    N1그룹 문자열,N2그룹 문자열은 hashset1,hashset2에 각각 추가로 입력받는다.
  2. chars를 하나씩 탐색하며 N1그룹을 기준으로, 현재 chars[j]가 N1그룹이고, 다음문자가 N2그룹 문자일때의 인덱스를 list에 넣어준다.
  3. list를 탐색하며, chars배열을 교체해준다.
  4. chars 배열을 StringBuilder를 통해 출력해준다.

후기

풀이 자체는 간단해보이지만 설계하는게 쉽지가 않았다.

profile
개린이

0개의 댓글