728x90
[Swift] 프로그래머스 [3차] 압축(lv. 2)
1. 문제
https://school.programmers.co.kr/learn/courses/30/lessons/17684
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
2. 접근
3. 코드
func solution(_ msg:String) -> [Int] {
var answer = [Int]()
let innerMsg = msg.compactMap({ String($0) })
var dict = [String : Int]()
for i in 1 ... 26 {
dict[String(UnicodeScalar(i + 64)!)] = i
}
var i = 0
var w = ""
while i < innerMsg.count {
let c = innerMsg[i]
let tempWC = w + c
if !checkInDict(w, c, dict) {
dict[tempWC] = dict.count + 1
answer.append(dict[w]!)
w = ""
continue
}
w += c
i += 1
}
answer.append(dict[w]!)
return answer
}
func checkInDict(_ w: String, _ c: String, _ dict: [String : Int]) -> Bool {
let wc = w + c
let isInDict = dict.contains(where: { $0.key == wc })
return isInDict
}
728x90
'Problem Solving' 카테고리의 다른 글
[Swift] 프로그래머스 [3차] n진수 게임(lv. 2) (0) | 2023.04.07 |
---|---|
[Swift] 프로그래머스 오픈채팅방(lv. 2) (0) | 2023.04.06 |
[Swift] 프로그래머스 연속 부분 수열 합의 개수(lv. 2) (0) | 2023.04.03 |
[Swift] 프로그래머스 타겟 넘버(lv. 2) (0) | 2023.04.01 |
[Swift] 프로그래머스 k진수에서 소수 개수 구하기(lv. 2) (0) | 2023.03.31 |
댓글