on
[알고리즘/백준] 1181 단어 정렬(자바)
[알고리즘/백준] 1181 단어 정렬(자바)
문제
https://www.acmicpc.net/problem/1181
풀이 코드
Stream API를 사용하여 중복제거, 정렬 distince() : 중복 제거 sorted() : 정렬
StringBuilder 사용을 통해 결과를 모아서 한번에 출력하여 실행 시간 단축
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); List list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(br.readLine()); } StringBuilder sb = new StringBuilder(); list.stream().distinct() .sorted((s1, s2) -> { if (s1.length() == s2.length()) { return s1.compareTo(s2); } else { return s1.length() - s2.length(); } }) .forEach(s -> sb.append(s).append("
")); System.out.println(sb); } }
728x90
from http://developer-hm.tistory.com/159 by ccl(A) rewrite - 2021-09-20 16:27:36