본문 바로가기
알고리즘/BOJ

[BOJ] 1181. 단어 정렬

by ㅣlㅣl 2024. 6. 25.

문제

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

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로 정렬
  • 단 중복 단어는 제거

 


 

주요 아이디어

  • cmp_to_key 라이브러리에 사용자 정렬 조건을 전달해 풀었다

 


 

코드 구현 (Python 3)

from functools import cmp_to_key

def compare(w1, w2):
    if len(w1) < len(w2):
        return -1
    elif len(w1) > len(w2):
        return 1
    else:
        if w1 < w2:
            return -1
        else:
            return 1

n = int(input())
word_list = [input() for _ in range(n)]

# 중복 제거
word_list = sorted(list(set(word_list)), key=cmp_to_key(compare))

for word in word_list:
    print(word)

 


 

제출 결과

 

'알고리즘 > BOJ' 카테고리의 다른 글

[BOJ] 1027. 고층 건물  (0) 2024.06.25
[BOJ] 5427. 불  (0) 2024.06.25
[BOJ] 10026. 적록색약  (0) 2024.06.25
[BOJ] 1351. 무한 수열  (0) 2024.06.25
[BOJ] 1541. 잃어버린 괄호  (0) 2024.06.25