Skip to content

숫자 짝꿍 #131128 #2

@chaentopia

Description

@chaentopia

🙋🏼 문제

숫자 짝꿍

💡 풀이

우선적으로 두 String을 Array로 만들어서 같은 것만큼 새 Array에 넣어줄 수 있도록 전략을 짰다.

if arr.isEmpty {
return "-1"
}
if arr.allSatisfy { $0 == "0" } {
return "0"
}
arr.sort(by: >)
let answer = arr.joined(separator: "")
return answer

위처럼 아무것도 없을 땐 -1이 출력되도록, "0"만 남아있다면 (ex. ["0", "0", "0"]) 0만 출력되도록 하였다.
arr를 큰 수부터 정렬하고, 하나의 String으로 합쳐주어 해당 값을 결과로 반환하였다.

근데 이제 arr에 넣는 과정이 어려웠다..

var xString = X.map { $0 }
var yString = Y.map { $0 }
var arr: [String] = []

xString와 yString를 map을 이용해서 [Character] 형태로 정리해주었고,
원래는 하나씩 검사해서 arr에 넣으려고 했는데, 도저히 방법을 찾을 수 없어서 array를 dictionary 형태로 바꿔주어 숫자가 몇번씩 등장했는지 카운트 하도록 하였다.
var xCount = [Character : Int]()
var yCount = [Character : Int]()
for item in xString {
xCount[item, default: 0] += 1
}
for item in yString {
yCount[item, default: 0] += 1
}

위처럼 ["0": 3, "1": 2, ... ] 형태의 dictionary를 만들었다.

for (key, xValue) in xCount {
if let yValue = yCount[key] {
let commonCount = min(xValue, yValue)
for _ in 0..<commonCount {
arr.append(String(key))
}
}
}

xCount와 yCount를 비교하여 둘 중 적은 수만큼 key 값을 arr에 추가해주었다.

진짜 코드가 너무 뚱뚱해져서 아쉬운 문제...

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions