N

(Leet Code JS)Decode Ways 본문

Leet Code 알고리즘

(Leet Code JS)Decode Ways

naeunchan 2022. 2. 18. 13:57
728x90
반응형

https://leetcode.com/problems/decode-ways/

 

Decode Ways - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

const numDecodings = (s) => {
    const length = s.length;
    const dp = Array(length + 1).fill(0);
    
    if(s[0] === "0"){
        return 0;
    }
    
    dp[length] = 1;
    dp[length - 1] = parseInt(s[length - 1]) ? 1 : 0;
    
    for(let i = length - 2; i >= 0; i--){
        const num = s.slice(i, i + 2);
        
        if(s[i] === "0"){
            dp[i] = 0;
        } else if(parseInt(num) <= 26){
            dp[i] = dp[i + 1] + dp[i + 2];
        } else{
            dp[i] = dp[i + 1];
        }
    }
    
    return dp[0];
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code JS)Can Place Flowers  (0) 2022.02.25
(Leet Code JS)Assign Cookies  (0) 2022.02.25
(Leet Code JS)Unique Paths II  (0) 2022.02.18
(Leet Code JS)Unique Paths  (0) 2022.02.18
(Leet Code JS)Jump Game II  (0) 2022.02.17