Programmers Algorithm - 둘만의 암호

Myung Jin Kim·2023년 10월 22일
0

문자열 s, 스킵해야 하는 문자열 skip, 특정 인덱스 만큼의 문자열 뒤의 알파벳으로 바꿔주기 위한 k 를 주고 결과값을 리턴해야 하는 문제다.

참조 : 둘 만의 암호

이를 처리하기 위해서는 특정 문자를 아스키 코드값으로 변환하는 방법, 그 역의 방법을 위한 메서드를 알아야 한다.

  • String.fromCharCode()
  • String.prototype.charCodeAt()

위의 메서드를 알면 알파벳 a 는 97, z 는 122 라는 것을 구할 수 있고 이를 통해 로직을 구현하면 된다.

const MIN_ALPHABET = 97;
const MAX_ALPHABET = 122;

function solution(s, skip, index) {
    const newStringArr = [];
    s.split('').forEach(eachChar => {
        let startCode = eachChar.charCodeAt(0);
        let startIndex = 0;
        while(true) {
            const nextCharCode = (startCode + 1) % (MAX_ALPHABET + 1);
            const calcNextCharCode = nextCharCode >= MIN_ALPHABET ? 
                  nextCharCode : MIN_ALPHABET + nextCharCode;
            const nextCode = String.fromCharCode(calcNextCharCode);
            startCode = nextCode.charCodeAt(0);
            
            if(skip.includes(nextCode)) {
                continue;
            } else {
                startIndex++;
                if(startIndex === index) {
                    newStringArr.push(nextCode);
                    break;
                }                
            }
        }
    });
    return newStringArr.join('');
}
profile
개발을 취미로 하고 싶은 개발자를 목표로 살고 있습니다

0개의 댓글