본문 바로가기
코딩 테스트/프로그래머스

둘만의 암호

by ornni 2024. 6. 8.
728x90
반응형

첫번째 코드

 

하나씩 알파벳을 미뤄보면서 skip안에 해당 알파벳이 있는 경우에 해당 개수만큼 추가로 더 밀어버린다.

 

def solution(s, skip, index):
    answer = ''
    skip_count = [0] * len(s)

    for i in range(len(s)):
        for j in range(1, index + 1):
            alpha = chr((ord(s[i]) + j - ord('a')) % 26 + ord('a'))
            if alpha in skip:
                skip_count[i] += 1

    for i in range(len(s)):
        answer += chr((ord(s[i]) + index + skip_count[i] - ord('a')) % 26 + ord('a'))

    return answer

 

엄청..많이 틀렸댜?


 

두번째 코드

 

틀린 이유는 만약에 skip에 b, c가 있는 경우에 a는 두번 밀리는데, 이전 코드는 b가 되어 한번만 밀리고 c에서 추가로 밀리지 않아 발생하는 문제였다!!!

그러므로 check라는 변수와 move라는 변수를 만든다.

move는 계속해서 하나씩 미뤄지지만 만약에 skip에 있지 않은 경우 check에 1씩 더해진다.

그래서 check가 index에 도달하면 더 이상 알파벳을 미루지 않고 정답에 더한다!

 

def solution(s, skip, index):
    answer = ''
    s = list(s)

    for _ in range(len(s)):
        check = 0
        move = 1
        while check != index:
            alpha = chr((ord(s[0]) + move - ord('a')) % 26 + ord('a'))
            if alpha not in skip:
                check += 1
                move += 1
            else:
                move += 1
        s.pop(0)
        answer += alpha

    return answer

 

통과!

인덱스? 같은 값을 두 개를 사용해야 해서 중간중간 응?엥? 했지만 그래도 정리하고 결과를 내니 뚜렷하게 보인다:)


링크

https://github.com/ornni/programmers/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/1/155652.%E2%80%85%EB%91%98%EB%A7%8C%EC%9D%98%E2%80%85%EC%95%94%ED%98%B8

 

programmers/프로그래머스/1/155652. 둘만의 암호 at main · ornni/programmers

repository for recording Programmers Algorithm problem solving - ornni/programmers

github.com

 

반응형

'코딩 테스트 > 프로그래머스' 카테고리의 다른 글

문자열 다루기 기본  (0) 2024.06.10
행렬 테두리 회전하기  (0) 2024.06.09
신고 결과 받기  (0) 2024.06.07
숫자 짝꿍  (0) 2024.06.06
N개의 최소공배수  (0) 2024.06.04