https://www.acmicpc.net/problem/1181
1181번: 단어 정렬
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
www.acmicpc.net
정말 간단한 문제인데, Dictionary, Sort 개념 잡기 좋은 문제
딕셔너리를 활용하여 입력된 단어들의 등장 횟수를 세는 예제입니다.
import Foundation
let n = Int(readLine()!)!
var dict = [String : Int]()
for _ in 0..<n {
let word = readLine()!
dict[word, default: 0] += 1
}
var sortedDict = dict.sorted {
$0.key.count == $1.key.count ? $0 < $1 : $0.key.count < $1.key.count
// 비교하는 2개 대상의 count 가 같으면, 사전순으로 정렬하고
// count 가 다르다면, 작은게 앞으로 가도록 정렬
}
for i in 0..<sortedDict.count {
print("\(sortedDict[i].key)")
}
dict[word, default: 0] += 1 부분에서 default: 0은 딕셔너리에서
word에 해당하는 키(key)의 값이 없을 경우,
즉 딕셔너리에 해당 키가 등록되어 있지 않을 때 기본값으로 0을 사용함을 의미
(딕셔너리의 subscript 문법을 사용한 것으로, 해당 키에 대한 값을 가져오거나 설정할 때 사용됨)
만약 word가 딕셔너리에 이미 등록되어 있다면 해당 값에 1을 더하고,
그렇지 않다면 새로운 키를 0으로 초기화한 후 1을 더한다.
이를 통해 각 단어의 등장 횟수를 세는 작업을 수행할 수 있음
(https://developer.apple.com/documentation/swift/dictionary/subscript(_:default:))
딕셔너리의 Subscript와 관련하여 자세한 블로그 글을 첨부하겠습니다.
아주 좋은 글이었어요!
https://eunjin3786.tistory.com/575
[Swift] Dictionary 의 subscript 3개 / KeyValuePairs
문서를 보면 Dictionary 의 subscript 로 세개가 구현되어있다. ✓ subscript(Key) -> Value? // get set ✓ subscript(Key, default _: () -> Value) -> Value // get set ✓ subscript(Dictionary.Index) -> Dictionary.Element // get 3번째처럼 ke
eunjin3786.tistory.com
'알고리즘' 카테고리의 다른 글
LeetCode - 104. Maximum Depth of Binary Tree (Swift) (1) | 2024.02.08 |
---|---|
LeetCode - 236. Lowest Common Ancestor of a Binary Tree (Swift) (0) | 2024.02.08 |
LeetCode - 160. Intersection of Two Linked Lists (Swift) (0) | 2024.01.19 |
프로그래머스 - 숫자짝궁 (Swift) (2) | 2024.01.09 |
[알고리즘] Python으로 LinkedList 구현하기 (0) | 2023.04.24 |