Focus On Develop ๐ŸคŸ๐ŸคŸ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์‹œ์ € ์•”ํ˜ธ ๋ณธ๋ฌธ

iOS [Swift]/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์‹œ์ € ์•”ํ˜ธ

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2020. 12. 21. 14:47

<๋ฌธ์ œ>


<์ „๋žต์งœ๊ธฐ>

์ผ๋‹จ ์•ŒํŒŒ๋ฒณ ๋Œ€์†Œ๋ฌธ์ž๋Š” ASCII์ฝ”๋“œ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์„œ, s๋ฅผ ๋Œ€/์†Œ๋ฌธ์ž ๋ฒ”์œ„์— ๋”ฐ๋ผ ์ฒดํฌํ•˜๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ๋ฐฉ๋ฒ•์ผ ๋“ฏ ํ•œ๋ฐ.. (๋‚˜๋Š” ASCII์ฝ”๋“œ๋ฅผ ์‚ฌ์‹ค ์ž˜ ๋ชจ๋ฆ„ ใ…‹) ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๋Š” ์–ด์ฐจํ”ผ ์•Œ๊ณ  ์žˆ๋Š” ๊ฑฐ๋‹ˆ๊นŒ ์ฐจ๋ผ๋ฆฌ ์•ŒํŒŒ๋ฒณ์„ ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋†“๊ณ , s์˜ ๋ฌธ์ž๋“ค์„ ์ฒดํฌํ•˜๋ฉด์„œ ์ •์˜ํ•ด๋‘” ์•ŒํŒŒ๋ฒณ ๋ฌธ์ž์—์„œ n๋งŒํผ ๋’ค์— ์žˆ๋Š” ๋ฌธ์ž๋กœ ๋Œ€์ฒดํ•˜๋Š” ๊ฑธ๋กœ ํ’€์–ด์•ผ๊ฒ ๋‹ค. z๋ฅผ ๋„˜์–ด๊ฐ€๋ฉด Out of Index๋‹ˆ๊นŒ.. ์›ํ˜•๋ฐฐ์—ด์ฒ˜๋Ÿผ % ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•ด์„œ Index๋ฅผ ์ฐพ์•„์•ผ๊ฒ ๋‹ค.

 

<์ฝ”๋“œ>

let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let lowerAlpha = alpha.lowercased()
let arrayAlpha = Array(alpha)
let arrayLowerAlpha = Array(lowerAlpha)

func solution(_ s:String, _ n:Int) -> String {
    var array = Array(s)
    for (i, x) in array.enumerated() {
        if alpha.contains(x) {
             array[i] = arrayAlpha[(Int(arrayAlpha.firstIndex(of: x)!)+n) % alpha.count]
        } else if lowerAlpha.contains(x) {
            array[i] = arrayLowerAlpha[(Int(arrayLowerAlpha.firstIndex(of: x)!)+n) % alpha.count]
        }
    }
    return String(array)
}

 

<Lesson Learned>

์ผ๋‹จ map์œผ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™์€๋ฐ ์ต์ˆ™์น˜ ์•Š์•„์„œ ์ผ๋‹จ ๋ฐฐ์—ด๋กœ ๋ฌธ์ œ ํ‘ผ ์ƒํ™ฉ.. ใ…œ.ใ…œ ๊ทธ๋ž˜์„œ ๊ทธ๋Ÿฐ์ง€ ์ฝ”๋“œ๊ฐ€ ๊ต‰์žฅํžˆ ๊น”๋”ํ•˜์ง€ ์•Š์€ ๋“ฏ(?) ํ•˜๋‹ค ใ…‹ใ…‹ map์œผ๋กœ ๋ฐ”๊ฟ”๋„ ๋กœ์ง์€ ๋˜‘๊ฐ™์ด ๋“ค์–ด๊ฐ€๊ธด ํ• ํ…๋ฐ..๋ณด๊ธฐ์— ๊น”๋”ํ•œ(?) ใ…Žใ…Ž ๊ทธ๋ฆฌ๊ณ  ์ด๋ฌธ์ œ๋Š” ์‹œ๊ฐ„์ œํ•œ or ๋ฉ”๋ชจ๋ฆฌ์ œํ•œ ์— ๋”ฐ๋ผ ์•ฝ๊ฐ„ ๋กœ์ง์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค. ์•„๋งˆ 2๊ฐ€์ง€๋Š” ์‹œ๊ฐ„/๋ฉ”๋ชจ๋ฆฌ๊ฐ€ Trade Off ์ธ.. ๐Ÿ˜ญ ๊ทธ๋ž˜๋„ ์ด ๋ฌธ์ œ๋Š” s์˜ ๊ธธ์ด๊ฐ€ ์ตœ๋Œ€ 8000 ์ด๋‹ˆ๊นŒ, ์ฐจ๋ผ๋ฆฌ lowerAlpha๋ฅผ ๋”ฐ๋กœ ์ •์˜ํ•ด๋†“๊ณ  ์œ„์˜ ํ’€์ด์ฒ˜๋Ÿผ ํ‘ธ๋Š”๊ฒŒ ๋‚˜์„ ๊ฒƒ ๊ฐ™๋„ค ๐ŸคŸ๐ŸคŸ

let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let arrayAlpha = Array(alpha)

func solution(_ s:String, _ n:Int) -> String {
    var originArray = Array(s)
    var array = Array(s)
    for (i, x) in array.enumerated() {
        if alpha.contains(x.uppercased()) {
            array[i] = arrayAlpha[(Int(arrayAlpha.firstIndex(of: Character(x.uppercased()))!)+n) % alpha.count]
        }
    }
    for (i, x) in originArray.enumerated() {
        if x.isLowercase {
            array[i] = Character(array[i].lowercased())
        }
    }
    return String(array)
}

 

 

 

์ถœ์ € : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์‹œ์ € ์•”ํ˜ธ

 

Comments