Where who wants to meet someone

백준 Swift [1181] 단어 정렬 본문

백준 알고리즘 문제 기록/정렬

백준 Swift [1181] 단어 정렬

Lust3r 2023. 8. 4. 15:29
728x90

난이도

실버 V

 

문제

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

 

1181번: 단어 정렬

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

www.acmicpc.net

 

내 답안

var alphabetSet = Set<String>()

for _ in 1...Int(readLine()!)! {
    alphabetSet.insert(readLine()!)
}

let sortedSet = alphabetSet.sorted(by: { first, second in
    if first.count < second.count {
        return true
    } else if first.count == second.count {
        return first < second
    } else {
        return first.count < second.count
    }
})

for i in sortedSet.indices {
    print(sortedSet[i])
}

- 중복 제거를 위해 Set을 사용했지만 정렬이 문제였다.

- count로 하고 난 다음에 어떻게 그 순서를 유지하면서 알파벳 순으로 맞출 수 있을까?

- 답은 sorted 메서드를 커스텀하는 것이었고, 메서드 내부에서 조건문으로 처리할 수 있었다.

- first가 second보다 글자수가 적으면 그대로 정렬하고, 같다면 String의 비교, 그 외의 경우(first의 글자수가 클 경우) 다시 count로 정렬하는 방법.