본문 바로가기

프로그래머스

[프로그래머스 Level 2] 튜플 [Java]

 

 


https://school.programmers.co.kr/learn/courses/30/lessons/64065/solution_groups?language=java&type=all 

 

프로그래머스

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

programmers.co.kr

 

※. 문자열을 배열로 만들어준다.

(substring, replace, replaceAll 등)

https://jamesdreaming.tistory.com/85

 

[ 자바 코딩 ] Java replace() vs replaceAll()

안녕하세요. 제임스 입니다. 이번에는 자바 String 관련 함수 중 특정 문자열을 원하는 문자열로 치환하는 함수에 대해 알아 보겠습니다. ■ String replace(CharSequence target, CharSequence replacement) rep..

jamesdreaming.tistory.com

 

※. 문자열 길이를 기준, 오름차순으로 정렬한다.

(Comparator을 이용한다.)

https://st-lab.tistory.com/243

 

자바 [JAVA] - Comparable 과 Comparator의 이해

아마 이 글을 찾아 오신 분들 대개는 Comparable과 Comparator의 차이가 무엇인지 모르거나 궁금해서 찾아오셨을 것이다. 사실 알고보면 두 개는 그렇게 어렵지 않으나 아무래도 자바를 학습하면서 객

st-lab.tistory.com

 

※. 중복되는 원소가 없는 튜플이기에, set을 사용해 중복되는 원소가 아닐 때만 값을 추가한다.

 


import java.util.Comparator;
import java.util.Arrays;
import java.util.HashSet;

class Solution {
    public int[] solution(String s) {
        int[] answer = {};
        String[] str = s.replaceAll("[{}]", " ").trim().split(" , ");    
	    Arrays.sort(str, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				return o1.length()-o2.length();
			}
	    	
	    });
	    
	    answer = new int[str.length];
	    int idx = 0;
	    HashSet<Integer> hashset = new HashSet<>();
	    for(String temp : str) {
	    	String[] str1 = temp.split("[,]");
	    	for(String temp1 : str1) {
	    		int a = Integer.parseInt(temp1);
	    		if(!hashset.contains(a)) {
	    			answer[idx++] = a;
	    			hashset.add(a);
	    		}
	    	}
	    }
	    
	    return answer;
    }
}