-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
💬 문제
[코딩테스트 연습 - 튜플](https://school.programmers.co.kr/learn/courses/30/lessons/64065)
💬 Idea
- 주어진 문자열을 배열로 변환한다.
- trimmingCharacters를 사용하여 양 끝에 “{”, “}”가 있는 부분들을 제거해준 뒤
- “},{” 라는 문자열이 튜플의 구분점이 되므로 해당 문자열을 기준으로 배열로 변환해준다.
- 이 때 원소들을 Int형으로 형변환해줘서 Int형의 숫자 원소를 만든다.
- 올바른 튜플의 순서를 반환하기 위해 튜플 이중 배열의 원소 개수가 작은 순으로 정렬을 해주고 for문을 돌며 정답을 도출한다.
💬 풀이
import Foundation
func solution(_ s:String) -> [Int] {
var tupleArr: [[Int]] = []
let s = s.trimmingCharacters(in: ["{", "}"]).components(separatedBy: "},{")
for i in s {
tupleArr.append(i.components(separatedBy: ",").map({ Int($0)! }))
}
tupleArr = tupleArr.sorted { $0.count < $1.count }
var resultArr: [Int] = []
for result in tupleArr {
for j in result {
if !resultArr.contains(j) {
resultArr.append(j)
}
}
}
return resultArr
}
💬 더 나은 방법?
import Foundation
func solution(_ s:String) -> [Int] {
var s = s
var answer = [Int]()
s.removeFirst(2)
s.removeLast(2)
s.components(separatedBy: "},{")
.map { $0.components(separatedBy: ",").map { Int($0)! } }
.sorted { $0.count < $1.count }
.forEach {
$0.forEach {
if !answer.contains($0) {
answer.append($0)
}
}
}
return answer
}
- 내코드랑 비슷한데 길이를 줄이신 코드!