ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์••์ถ•(Swift)

2022. 10. 18. 00:31ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์••์ถ•(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/17684

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

์ด ๋ฌธ์ œ๋Š” ํ’€๊ธด ํ–ˆ์ง€๋งŒ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๋ฅผ์— ๋„๋‹ฌํ–ˆ์„ ๋•Œ breakํ•œ ํ›„ ์ฒ˜๋ฆฌ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ•˜๋Š”์ง€ ์ž˜ ๊ฐ์ด ์•ˆ์™€์„œ ์‹œ๊ฐ„์ด ์กฐ๊ธˆ ๊ฑธ๋ ธ๋‹ค.

๋ฌธ์ œ์˜ ์š”๊ตฌ์‚ฌํ•ญ๋Œ€๋กœ ๊ตฌํ˜„๋งŒ ํ•˜๋ฉด ๋˜์ง€๋งŒ ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ๋งŒ๋‚˜๊ฒŒ ๋˜๋ฉด ๊ทธ๋ฆผ์„ ๊ทธ๋ ค๋ณด๋ฉด์„œ ๋น ๋ฅด๊ฒŒ ํ•ด๊ฒฐํ•˜๋Š” ๊ฒŒ ์ข‹์€๋“ฏํ•˜๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ UnicodeScalar๋ฅผ ์ด์šฉํ•ด์„œ A~Z๊นŒ์ง€ ์„ ์–ธํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์ต์ˆ™ํ•ด์ง€๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

 

func solution(_ msg:String) -> [Int] {
    
    var dic: [String: Int] = [:]
    (0...25).forEach { i in
        let key = String(UnicodeScalar(65+i)!)
        dic[key] = i+1
    }
    
    var answer: [Int] = []
    
    let arr = Array(msg).map{ String($0) }
    var idx = 0
    var str = arr[0]
    while true {
        if idx == arr.count-1 { 
            break 
        }
        if dic[str] != nil {
            str += arr[idx+1]
            idx += 1
        } else {
            dic[str] = dic.values.max()! + 1
            str.removeLast()
            answer.append(dic[str]!)
            str = arr[idx]
        }
    }
    
    if dic[str] != nil {
        answer.append(dic[str]!)
    } else {
        str.removeLast()
        answer.append(dic[str]!)
        answer.append(dic[arr[idx]]!)
    }
    
    return answer
}

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

 ํ”ผ๋“œ๋ฐฑ