프로그래머스 튜플

2021. 1. 2. 12:38알고리즘

튜플 : programmers.co.kr/learn/courses/30/lessons/64065

 

코딩테스트 연습 - 튜플

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

해당 문제는 집합이 표현하고자하는 숫자의 순서?를 지켜서 출력하는 문제였다.

따라서 "{{4,2,3},{3},{2,3,4,1},{2,3}}"이런식으로 들어오는 문자열을 잘 파싱하여 원소의 사이즈로 정렬을 한뒤에 만족하는 문자를 배열에 추가 해주었다.

 

집합의 원소는 1이상 100000이하 이기 때문에 일단 100001크기의 배열을 만들어  원소의 갯수를 세줌으로 중복을 방지하였다.

import java.util.*;

class Solution {
   	public List<String[]> list = new ArrayList<>();
	public int[] numsCount = new int[100001];

	public int[] solution(String s) {

		String[] strArr = s.split("},");
		for (int i = 0; i < strArr.length; i++) {
			String temp = strArr[i].replaceAll("[{}]", "");
			String[] sArr = temp.split(",");

			list.add(sArr);
		}
		int[] answer = new int[list.size()];

		Collections.sort(list, new Comparator<String[]>() {

			@Override
			public int compare(String[] o1, String[] o2) {
				if (o1.length < o2.length) {
					return -1;
				}
				return 1;
			}

		});

		for (int i = 0; i < list.size(); i++) {
			int[] copiedNumCount = numsCount.clone();
			String[] temp = list.get(i);

			for (int j = 0; j < temp.length; j++) {
				int num = Integer.parseInt(temp[j] + "");
				if (copiedNumCount[num] == 0) {
					numsCount[num]++;
					answer[i] = num;
					break;
				} else {
					copiedNumCount[num]--;
				}
			}

		}
		return answer;
	}
}

해당 문제 역시 문자열 처리를 공부하기위해 좋은 문제 였던것 같다.

 

문제를 풀며 알게된점은 String.replaceAll은 정규식을 허용한다는 점이 었다. 따라서"[{}]"의 말은 '{'와 '}'을 모두""로 바꿔주세요 라는 의미이다. 

찾아보니 정규식을 허용하는점이 replace와 replaceAll의 차이점이라고 한다.