Live Today

[백준] 1181. 단어 정렬 (Java) 본문

알고리즘/백준 문제풀이

[백준] 1181. 단어 정렬 (Java)

ilivetoday 2023. 2. 12. 16:17
반응형

https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

 

 

💡 문자열 정렬 알고리즘 문제 !

- Collections.sort()를 활용해 input값의 문자열을 사전 순으로 정렬함.
- PrirorityQueue를 활용해 단어의 길이가 같다면 문자열로 정렬되도록 설정함.

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;

public class Main_bj_1181_단어정렬 {
	
	static int N;
	static class Word implements Comparable<Word>{
		int len, index;
		String s;
		public Word(int len, int index, String s) {
			this.len = len;
			this.index = index;
			this.s = s;
		}
		
		public int compareTo(Word o) {
			if(this.len == o.len) return this.index - o.index;
			return this.len - o.len;
		}
	}

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		N = Integer.parseInt(br.readLine());
		ArrayList<String> wordList = new ArrayList<>();
		for(int i=0;i<N;i++) {
			String temp = br.readLine();
			
			// 문자열 중복 제거
			if(wordList.contains(temp)) continue;
			wordList.add(temp);
		} // input end
		
		// 문자열 정렬을 위한 sort함수 사용
		Collections.sort(wordList);
		//System.out.println(wordList);
		
		PriorityQueue<Word> pq = new PriorityQueue<>();
		for(int i=0;i<wordList.size();i++) {
			pq.add(new Word(wordList.get(i).length(), i, wordList.get(i)));
		}
		
		while(!pq.isEmpty()) {
			Word tmp = pq.poll();
			String result = tmp.s;
			sb.append(result+"\n");
		}
		
		System.out.println(sb.toString());
	}

}