나 JAVA 봐라

[프로그래머스] 튜플 본문

카테고리 없음

[프로그래머스] 튜플

cool_code 2024. 8. 28. 15:33

https://school.programmers.co.kr/learn/courses/30/lessons/64065

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 이해하는데 한참 걸림;;; ....

 

내가 생각한 풀이 순서는 아래와 같다. 

1. String s를 substring, split 등을 통해 변환하여 ArrayList<int[]> 에 넣기

2. 변환한 list를 int[] 배열 크기 순서대로 정렬하기

3. 순서대로 수를 담아서 출력하기

 

이중 for문도 많고 코드 자체도 많이 더럽지만 일단 통과는 했다... 

import java.util.*;

class Solution {
    public int[] solution(String s) {
        // 원소 하나만 있으면 0번째 인덱스 원소
        // 그 다음에 붙어있으면 다음 인덱스 원소.. -> 중복 x
        
        // 1. String 잘라서 ArrayList<int[]> 에 넣기
        String sub_s = s.substring(2,s.length()-2);
        String str[] = sub_s.split("\\},\\{"); // 중괄호는 이스케이프 두번 써줘야함... 
        
        ArrayList<int[]> list = new ArrayList<>();
        
        for (int i = 0; i < str.length; i++){
            String before_str[] = str[i].split(","); 
            int aft_str[] = new int[before_str.length];
            for(int j = 0; j < before_str.length; j++){
                aft_str[j] = Integer.parseInt(before_str[j]);
            }
            list.add(aft_str);
        }
        
        // int[]의 크기 순서대로 정렬하기
        Collections.sort(list,(x,y)-> x.length - y.length);
        
        int[] answer = new int[list.size()];
        HashSet<Integer> hs = new HashSet<>();
        
        for (int i = 0; i < list.size(); i++){
            int value[] = list.get(i);
            for (int val : value){
                if (!hs.contains(val)){
                    answer[i] = val;
                    hs.add(val);
                    break;
                }
            }
        }
        
        return answer;
    }
}