백준 자바 1181 단어 정렬

김재동·2024년 7월 15일
0

문제

목록 보기
9/16


이 문제도 정렬하는 문제이므로, 이전 문제들 처럼 우선순위 큐를 사용해야겠다고 생각했다. 다만, 그 과정에서 문자열의 길이<를 기준으로 1차 정렬하고, 만약 길이가 같으면 사전 순이며, 중복된 단어는 하나만 남기고 제거해야되므로 총 세 가지 조건을 고려해야되는 문제이다.

package test12;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

public class Ox12_Q3_1 {
	// 백준 1181 S5 단어 정렬
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int n = Integer.parseInt(br.readLine());
		String [] str = new String[n];
		Set<String> set = new HashSet<>(); // 중복 단어 제거용 Set
		PriorityQueue<word> prique = new PriorityQueue<>(1, new wordComparator());
		
		// 값 입력 부분
		for(int i = 0 ; i<n; i++) {
			String temp = br.readLine();
			// 값이 중복이 아니라서 정상적으로 들어가는 경우
			if(set.add(temp)) { 
				prique.offer(new word(temp,temp.length()));
			}
		}// for fin
		br.close();
		
		// 출력 부분
		while(!prique.isEmpty()) {
			word w = prique.poll();
			sb.append(w.word).append("\n");
		}// while fin
		System.out.println(sb.toString().trim());
	}
}

class word{
	String word;
	int wordLen;
	
	word(String word, int wordLen){
		this.word = word;
		this.wordLen = wordLen;
	}
}

class wordComparator implements Comparator<word>{
	@Override
	public int compare(word w1, word w2) {
		// 길이가 같은 경우 -> 사전 순 정렬
		if (w1.wordLen == w2.wordLen) {
			return w1.word.compareTo(w2.word);
		} 
		// 기존 -> 문자열 길이 정렬
		else {
			return w1.wordLen - w2.wordLen;
		}
	}
}

구문 자체는 그렇게 복잡하진 않다.
prique(우선순위 큐)에 입력받은 값과 해당 길이를 넣어주고,
출력하면서 정렬한다. 이 과정에서 중복을 바로 제거하기 위해
Hashset 형태로 입력한다.

이때 우선순위 큐의 코드는 먼저 길이가 같으면
사전 순으로 comparTo 함수를 통해 작은 값이 먼저 출력되게끔 하고,
길이가 다르면, 문자열 길이를 기준으로 정렬된다.

굿

profile
성장중

0개의 댓글