728x90
프로그래머스 [1차] 뉴스 클러스터링
각 문자열을 2글자 단위로 끊어서 합집합과 공집합을 통해 자카드 유사도를 구하는 문제입니다.
Set의 집합 관련 메소드를 사용하면 결과 값이 달라서 순회로 구현했습니다.
func solution(_ str1:String, _ str2:String) -> Int {
let str1 = str1.lowercased().reduce(into: [" "]) {
$0.append("\\($0.last!.last!)\\($1)")
}.filter {
$0.first!.isLetter && $0.last!.isLetter
}
var str2 = str2.lowercased().reduce(into: [" "]) {
$0.append("\\($0.last!.last!)\\($1)")
}.filter {
$0.first!.isLetter && $0.last!.isLetter
}
let a = str1.reduce(into: 0) { result, element in
if str2.contains(element) {
result += 1
str2.remove(at: str2.firstIndex(of: element)!)
}
}
if str1.count + str2.count == 0 {
return 65536
}
else {
return Int(Double(a) / Double(str1.count + str2.count) * 65536.0)
}
}
print(solution("AAbbaa_AAbb", "BBB"))
// str1 str2 answer
// FRANCE french 16384
// handshake shake hands 65536
// aa1+aa2 AAAA12 43690
// E=M*C^2 e=m*c^2 65536
728x90
'Algorithm' 카테고리의 다른 글
파이썬 알고리즘 문법 (0) | 2025.03.30 |
---|---|
Swift 알고리즘 관련 문법 (0) | 2025.03.30 |
SwiftUI: [1차] 캐시 (0) | 2024.04.03 |
SwiftUI: 의상 (0) | 2024.04.02 |
SwiftUI: H-Index (0) | 2024.04.02 |