[프로그래머스]튜플

allnight5·2023년 5월 14일
0

프로그래머스

목록 보기
66/73

링크

내가 작성한거

import java.util.*;
class Solution {
    public int[] solution(String s) {
        int sLength = s.length();
        s = s.substring(1,sLength-1);
        s = s.replace("}", "");
        String[] sSplit = s.split("\\{");
        Map<Integer, String[]> map = new HashMap<>();
        for(int i=1; i<sSplit.length;i++){
            String[] str = sSplit[i].split(","); 
            map.put(str.length, str);  
        }
        
        List<String> resultList = new ArrayList<>();
        resultList.add(map.get(1)[0]); 
        
        for(int i=2; i<map.size()+1;i++){
            String[] s2 = map.get(i);
            List<String> result2 = Arrays.asList(s2);
            for(String str: result2){
                if(!resultList.contains(str)){
                    resultList.add(str);
                    break;
                }
            } 
        } 
        String[] resultString = resultList.toArray(new String[resultList.size()]); 
        return Arrays.stream(resultString).mapToInt(Integer::parseInt).toArray();
    }
}

다른 좀 더 함수에 대한 이해가 깊으신분꺼

import java.util.*;
class Solution {
    public int[] solution(String s) {
        Set<String> set = new HashSet<>();
        String[] arr = s.replaceAll("[{]", " ").replaceAll("[}]", " ").trim().split(" , ");
        Arrays.sort(arr, (a, b)->{return a.length() - b.length();});
        int[] answer = new int[arr.length];
        int idx = 0;
        for(String s1 : arr) {
            for(String s2 : s1.split(",")) {
                if(set.add(s2)) answer[idx++] = Integer.parseInt(s2);
            }
        }
        return answer;
    }
}
profile
공부기록하기

0개의 댓글