본문 바로가기

iOS 앱 개발자 프로젝트/알고리즘 코드카타

[Algorithm] 둘만의 암호 (w/ Swift & Python)

 

둘만의 암호 (shortcuts) 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

language = swift

 

스위프트에서 문자열  ↔️  아스키코드 변환 

String to Ascii: Int(UnicodeScalar("A").value)
Ascii to String: String(UnicodeScalar(65)!)

 

import Foundation

func solution(_ s:String, _ skip:String, _ index:Int) -> String {
    // a,z 아스키코드 구해놓기
    var aAscii = Int(UnicodeScalar("a").value) 
    var zAscii = Int(UnicodeScalar("z").value) 
    
    // skip 문자들 아스키로 바꿔두기
    var skipAscii = skip.map { Int(UnicodeScalar(String($0))!.value)  }
    

    var answer = ""
    
    for v in s {
        // 현재 문자의 아스키코드
        var ascii = Int(UnicodeScalar(String(v))!.value)
        // index만큼 더했는지 확인하는 변수
        var indexCnt = 0
        
        // 아스키코드를 1씩 더하는 loop
        while indexCnt < index {
            ascii += 1

            // z아스키 넘었는지 체크
            if ascii > zAscii {
                ascii = aAscii
            }
            
            // 건너뛰어야하는 문자열이면 indexCnt 증가 X
            if skipAscii.contains(ascii) {
                continue
            } else {
                indexCnt += 1
            }
            
        }
        
        // 다시 문자열로 변환해서 append
        answer.append(String(UnicodeScalar(ascii)!))
    }

    return answerString
}

 

 

 

 

language = python

def solution(s, skip, index):
    result = ''
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    remaining_alphabet = [c for c in alphabet if c not in skip]

    for sb in s :
        if sb in remaining_alphabet :
            index_in_remaining = (remaining_alphabet.index(sb) + index) % len(remaining_alphabet)
            result += remaining_alphabet[index_in_remaining]

    return result

#1

알파벳을 배열에 넣고 remove() 메서드로 skip에 해당하는 문자를 제거

 

#2

index값을 더했을 때 alphabet 배열보다 큰지 작은지 비교하여 그에 맞게 분기처리

 

#3

s문자열에 있는 각 문자의 index값과 입력받는 index값을 더한 값이 alphabet 배열 길이보다 클 때 len(alphabet)을 빼는 것이 아닌 나눈 나머지로 해결하면 완성 .. ♡