문제 풀이
- 순차적으로 튜플이 생성되는 과정?을 string으로 넘겨받는다.
- 이제 순서대로 그 튜플의 완성본을 출력하면 된다 !
문제 접근
- 순차적으로 생기니까 이 나오는 빈도수로 판단해주면 될 것 같다고 생각을 했다.
- 근데 먼저
"{{2},{2,1},{2,1,3},{2,1,3,4}}"
이런식으로 넘겨주고 있어서 이걸 일반적인 형태로 치환을 해줘야한다.replacingOccurrences
를 사용해보자
문제 풀이
처음에는 이제 "{{2},{2,1},{2,1,3},{2,1,3,4}}"
이렇게 괴랄하게 들어오는 친구를 어떻게 처리해주지 싶었는데, 빈도수로 처리를 해주려고 생각을 하니까 일단 {
, }
를 싹 지워주고, ,
남은 쉼표로 split을 해주면 쉽게 될 것 같았다.
치환할때 사용하는 replacingOccurences
활용
var a = s.replacingOccurrences(of: "{", with: "").replacingOccurrences(
of: "}",
with: ""
).split(separator: ",")
var dict = [String: Int]()
for item in a {
dict[String(item), default: 0] += 1
}
return dict.sorted(by: { $0.value > $1.value }).map { Int($0.key)! }
최종코드
import Foundation
func solution(_ s: String) -> [Int] {
var a = s.replacingOccurrences(of: "{", with: "").replacingOccurrences(
of: "}",
with: ""
).split(separator: ",")
var dict = [String: Int]()
for item in a {
dict[String(item), default: 0] += 1
}
return dict.sorted(by: { $0.value > $1.value }).map { Int($0.key)! }
}
채점 결과
정확성: 100.0
합계: 100.0 / 100.0
타인의 코드
import Foundation
func solution(_ s:String) -> [Int] {
var result: [Int] = []
var sets = s.split(omittingEmptySubsequences: true, whereSeparator: { "}".contains($0) }).map {
$0.split(omittingEmptySubsequences: true, whereSeparator: { "{,".contains($0) }).map { Int($0)! }
}
sets.sort { (lhs, rhs) -> Bool in
lhs.count < rhs.count
}
sets.forEach {
result.append(Array(Set($0).subtracting(result)).first!)
}
return result
}
문자열울 배열로 치환해주는 과정에서 사용한 메소드의 차이
replacingOccurrences
var a = s.replacingOccurrences(of: "{", with: "").replacingOccurrences(
of: "}",
with: ""
).split(separator: ",")
,
를 기준으로 문자열 나누기split
사용var sets = s.split(omittingEmptySubsequences: true, whereSeparator: { "}".contains($0) }).map {
$0.split(omittingEmptySubsequences: true, whereSeparator: { "{,".contains($0) }).map { Int($0)! }
}
}
를 기준으로 문자열 split, omittingEmptySubsequences
true해줘서 문자열 공백 제거나와 같은 궁금증을 가지신분이 이렇게 쓴 글도 있으니 참고하면 좋을 것 같다. 결론은
replacingOccurrences(of: " ", with: "") is better than components(separatedBy: .whitespaces).joined() in time complexity too. This is partially because replacingOccurrences(of:with:) is defined on NSString and not String. In a sense it's like comparing 🍏🍎 to 🍊🍊.
시간 복잡성 측면에서도 replacingOccurrences(of: “ ‘, with: ’”)가 components(separatedBy: .whitespaces).joined()보다 낫습니다. 이는 부분적으로 replacingOccurrences(of:with:)가 문자열이 아닌 NSString에 정의되어 있기 때문입니다. 어떤 의미에서는 🍏🍎와 🍊🍊를 비교하는 것과 같습니다.
나는 Dictonary 활용해서 정렬을 통해 수행했는데, 아마 출제 의도에 맞춘거는 이분의 subtracting인것같았다.
sets.forEach {
result.append(Array(Set($0).subtracting(result)).first!)
}
계속 집합이 성장하는 형태(계속 있던거에 덧붙여지는 형태)를 띄고 있으니 작은 SET부터 차근차근 원래 있던거를 새로 들어온 친구로부터 차집합을 구해주면 있던놈이 나가기 때문에 이걸 배열로 하나하나씩 추가해주는 구조다
예를들어
[1], [1,2], [1,2,3] 이 있으면
[1] 이 들어오고 이제 [1,2].subtracting([1])을 해주면 2가 남아서 이걸 배열에 append해주는 구조라고 보시면될 것 같다!