clean c++ code


  • 0
    D
    class Solution {
    public:
        int numDecodings(string s) {
            int n = s.size(), base = pow(10, 9) + 7;
            vector<long> dp(n + 1);
            dp[0] = 1;
            if (s[0] == '0') dp[1] = 0;
            else if (s[0] == '*') dp[1] = 9;
            else dp[1] = 1;
            
            for (int i = 2; i <= n; i++) {
                char c1 = s[i - 2]; //十位
                char c2 = s[i - 1]; //个位
                // lenth 1 case
                if (c2 == '*') {
                    dp[i] += 9 * dp[i - 1]; 
                }
                else if (c2 >= '1' && c2 <= '9') {
                    dp[i] += dp[i - 1];
                }
                // length 2 case
                if (c1 != '*' && c2 != '*') {
                    int num = stoi(string(1, c1) + string(1, c2));
                    if (num >= 10 && num <= 26) {
                        dp[i] += dp[i - 2];
                    }
                }
                else {
                    if (c1 == '*') { 
                        if (c2 == '*') dp[i] += 15 * dp[i - 2]; // **
                        else if (c2 > '6') dp[i] += dp[i - 2]; // *7 
                        else dp[i] += 2 * dp[i - 2]; // *1
                    }
                    else if (c1 == '1') {
                        dp[i] += 9 * dp[i - 2];
                    }
                    else if (c1 == '2') {
                        dp[i] += 6 * dp[i - 2];
                    }
                }
                dp[i] %= base;
            }
            return dp[n] % base;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.