[백준 2DimensionArray] 10798번 문제

Kwon·2023년 11월 27일

백준

목록 보기
15/22
post-thumbnail

백준 10798번 문제

풀이

  • 총 5행에 거친 단어들을(15글자 제한) 세로로 출력하는 문제
  • 2차 배열을 이용해 각 열마다 순서대로 1~5행 글자를 읽어야 함
  • 15글자 제한을 파악하지 못하고 동적으로 글자 설정했다가 오래 걸린 문제이다 (결국 동적으로 설정하긴 함)
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] word = new String[5];
        ArrayList<Character>[] list = new ArrayList[5];
        int max = 0;

        for (int i = 0; i < 5; i++) {
            word[i] = sc.next();
            list[i] = new ArrayList<Character>();
            if (word[i].length() > max) max = word[i].length();
        }

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < word[i].length(); j++) {
                list[i].add(word[i].charAt(j));
            }
            while(list[i].size() < max) list[i].add('\0');
        }

        int i = 0;
        while(i < max) {
            for (int j = 0; j < 5; j++) {
                if(list[j].get(i) == '\0') continue;
                System.out.print(list[j].get(i));
            }
            i++;
        }
    }
}

1. 배열 설정

Scanner sc = new Scanner(System.in);
String[] word = new String[5];
ArrayList<Character>[] list = new ArrayList[5];
int max = 0;
  • 단어 입력 받을 String형 배열 5개 선언
  • 열의 길이를 유추할 수 없으므로 동적으로 변수 선언
  • 2차 배열의 열 기준을 문제 풀기 쉽게 만들기 위해 정수형 max 선언

2. 입력 받기

for (int i = 0; i < 5; i++) {
    word[i] = sc.next();
    list[i] = new ArrayList<Character>();
    if (word[i].length() > max) max = word[i].length();
}
  • 인스턴스로 list 선언해줬기 때문에 for문에서 각각 동적 list char형으로 선언
  • 열의 기준을 맞추기 위해 제일 긴 단어 기준으로 max를 잡음

3. 동적 할당

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < word[i].length(); j++) {
        list[i].add(word[i].charAt(j));
    }
    while(list[i].size() < max) list[i].add('\0');
}
  • 5개 배열에 입력 받았던 단어들을 동적 배열에 할당
  • 열의 기준을 맞추기 위해 각 행의 빈 자리는 null값 선언
    (ex. 3 4 5 4 3이라면 제일 긴 단어 값 5의 기준을 맞춰 5의 길이가 되게 끔 Null 값 선언)

4. 단어 출력

int i = 0;
while(i < max) {
    for (int j = 0; j < 5; j++) {
        if(list[j].get(i) == '\0') continue;
        System.out.print(list[j].get(i));
    }
    i++;
}
  • 열 기준으로 행 순서대로 단어를 출력해야 하니 while 조건문을 max로 설정
  • 만일 null 값 확인 시 무시
  • 출력은 list[j].get(i) 형식으로 각 열마다의 행을 출력할 수 있다.

**총총

  1. 문제를 잘 파악하면 쉽지만 이상하게 파악하면 어려운 문제 같다.
  2. 난이도 실버5급 문제(백준 기준)
  3. 더 괜찮게 짤 수 있고 시간이 생각보다 오래 걸려 아쉬움이 남은 문제

profile
📲 @bu_kwon_2 / 💻 dnu05043.log / ⌨ Back-end / 🦁 LikeLion

0개의 댓글