1309. Decrypt String from Alphabet to Integer Mapping (leet code)

임병욱·2023년 11월 21일
0

algorithm

목록 보기
6/31

문제 설명

You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:

Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.

The test cases are generated so that a unique mapping will always exist.

제한 사항

  • 1 <= s.length <= 1000
  • s consists of digits and the '#' letter.
  • s will be a valid string such that mapping is always possible.

입출력 예

내 풀이

/**
 * @param {string} s
 * @return {string}
 */
var freqAlphabets = function(s) {
    let answer = ''

    for (let i = s.length - 1; i >= 0; i--) {
        let str = s.charAt(i);

        if (str === '#') {
            str = s.charAt(i - 2) + s.charAt(i - 1);
            i -= 2;
        }

        const number = parseInt(str);
        const value = String.fromCharCode(number + 96);
        answer = value + answer

    }

    return answer    
};

회고

#앞의 숫자들을 처리하기 어려웠다. 뒤에서부터 for문을 돌리며 #을 만날 때는 앞의 두 문자를 합친 뒤 i -= 2하여 순호의 index를 점프시킨다.
그리고 매번 문자열을 뒤에서만 추가하였는데 앞에 추가하는 방법은 생각해본 적이 없었다. 단순히 코드로 answer = value + answer만 해주면 됐다.

profile
안녕하세여

0개의 댓글