알고리즘/알고리즘 문제풀이

문자열_프로그래머스_시저 암호 [swift]

Downey 2022. 5. 18. 13:36

https://programmers.co.kr/learn/courses/30/lessons/12926

접근 방법

  1. 대, 소문자 알파벳 배열을 준비
  2. s의 각 요소에 대하여, 조건문에 따른 수행
  3. 대, 소문자일 경우, 적합한 Array에서 index를 찾고, index + n 한 뒤 Array.count만큼 % 연산한다. 이를 통해 z를 넘어간 경우를 커버 할 수 있음.
  4. sol에 변환된 String이 저장되며, 이를 반환.

 

정답 코드

더보기
    func solution(_ s:String, _ n:Int) -> String {
        
        let lowerAlphabet = "abcdefghijklmnopqrstuvwxyz"
        let lowerBand = Array(lowerAlphabet)
        let upperBand = Array(lowerAlphabet.uppercased())
        
        var sol : String = .init()
        
        for cha in s {
            if cha.isUppercase {
                
                    if let now = upperBand.firstIndex(of: cha) {
                        let next = (now + n) % upperBand.count
                        sol.append(upperBand[next])
                    }
            }
            
            if cha.isLowercase {
                if let now = lowerBand.firstIndex(of: cha) {
                    let next = (now + n) % lowerBand.count
                    sol.append(lowerBand[next])
                }
            }
            
            if cha.isWhitespace {
                sol.append(cha)
            }
        }
        return sol
    }