Algorithm/프로그래머스

[프로그래머스 스위프트] 시저암호

devKen 2022. 9. 15. 22:51

아이디어

스위프트의 문자열이 복잡하다고 알고 있다면 조금 어폐가 있다. 쉽게 쓸 수 있는 방법도 존재한다. 파이썬으로 한번 풀었던 거라 어떻게 풀지는 이미 알았던 문제였다. 무자가 총 26개라는 것에 주목하여 글자의 인덱스 번호와 n의 덧셈이 26을 넘을 때 동작하게 만든다.

해답

func solution(_ s:String, _ n:Int) -> String {
    let upper = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    let lower = Array("abcdefghijklmnopqrstuvwxyz")
    var result  = ""
    for ch in s {
        if upper.contains(ch) {
            var index = upper.firstIndex(of: ch)! + n
            if index > 25 {
                index -= 26
            }
            result.append(upper[index])
        } else if lower.contains(ch) {
            var index = lower.firstIndex(of: ch)! + n
            if index > 25 {
                index -= 26
            }
            result.append(lower[index])
        } else {
            result.append(ch)
        }
    }
    return result
}