[프로그래머스 / Level2] 튜플 (Java)

wannabeking·2022년 7월 12일
0

코딩테스트

목록 보기
48/155

문제 보기



사용한 것

  • 주어진 문자열을 int 배열들로 쪼개어 저장하기 위한 문자열 파싱


풀이 방법

  • 문자열을 파싱하여 int 배열을 map에 넣고 idx를 1씩 증가 시킨다.
    • map의 key는 배열의 길이 - 1, value는 배열이다.
  • map의 key 0 ~ idx - 1 만큼 int 배열을 꺼낸다.
    • int 배열을 돌며 set에 없으면 추가시키고 answer의 해당 인덱스에 넣어준다.
  • answer을 반환한다.


코드

class Solution {

    public int[] solution(String s) {
        Map<Integer, int[]> map = new HashMap<>();
        int idx = 0;
        String string = "";
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '}') {
                String[] split = string.split(",");
                map.put(
                    split.length - 1,
                    Arrays.stream(split)
                        .mapToInt(Integer::parseInt)
                        .toArray()
                );
                string = "";
                idx++;
                i++;
            } else {
                if (c != '{') {
                    string += c;
                }
            }
        }

        int[] answer = new int[idx];
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < idx; i++) {
            for (int num : map.get(i)) {
                if (!set.contains(num)) {
                    answer[i] = num;
                    set.add(num);
                }
            }
        }

        return answer;
    }
}


profile
내일은 개발왕 😎

0개의 댓글