백준 20291번 파일 정리

김종완·2022년 5월 14일
1

https://www.acmicpc.net/problem/20291

문제를 풀기위해 사용한 방법


해당 문제를 풀기 위해서 문자열이 담긴 배열을 정렬하고, 비슷한 종류의 수가 인접해있다는 원리를 이용해서 문제를 해결 했습니다.
<소스코드>

package solveByType.sort;

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class organizeFile_20291_bak {
    static FastReader scan = new FastReader();
    static StringBuilder sb = new StringBuilder();

    static void input(){
        N = scan.nextInt();
        files = new String[N+1];
        for(int i=1; i<=N; i++) files[i] = scan.nextLine();
        files[0] = "";
    }

    static int N;
    static String[] files;

    static void pro(){
        // 필요한 정수
        int count = 1;
        String now_str = files[1];

        for(int i=1; i<=N; i++) {
            files[i] = files[i].split("\\.")[1];
        }

        // 파일 정렬
        Arrays.sort(files,1, N+1);

        // 특정 파일이 몇개 있는지 개수 세기
        for(int i=2; i<=N; i++){
            if(files[i].equals(files[i-1])) {
                count++;
            } else{
                sb.append(files[i-1]).append(" "+count).append("\n");
                count = 1;
            }
        }
        if(count > 1 || files[N] != files[N-1]){
            sb.append(files[N]).append(" "+count).append("\n");
        }

        System.out.println(sb.toString());
    }

    public static void main(String[] args){
        input();
        pro();
    }

    static class FastReader{
        BufferedReader br;
        StringTokenizer st;

        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {return Integer.parseInt(next());}
        long nextLong() {return Long.parseLong(next());}
        double nextDouble() {return Double.parseDouble(next());}

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

마주첬던 오류


해당 문제를 풀던중 파일 확장자만 추출하기 위해서 split을 사용하였고 "."을 사용해서 문자열을 구분하였다. 하지만 split 결과 리턴값은 [] 아무것도 들어있지않은 배열이였다. 그이유를 찾아보니 "." 같은경우는 정규 표현식으로 나타내야 되는데 [.], \\. 이런 식으로 .을 찍어야 된다.

profile
개발에 재미를 느끼며 꾸준히 성장하는 개발자 김종완 입니다.

0개의 댓글