C++ 0ms solution, O(1) space


  • 0
    C

    class Solution {
    public:
    int numDecodings(string s) {
    int size = s.size();
    int result = 0;
    int pre_left=1, pre_right=1;
    char pre_char = '9';
    if(size < 1)
    return 0;
    for(int i=0; i<size; i++){
    int temp = (pre_char-'0')*10 + (s[i]-'0');
    if(pre_char=='0' && s[i]=='0')
    result = 0;
    else if(pre_char == '0')
    result = pre_right;
    else if(s[i] == '0'){
    if(pre_char < '3')
    result = pre_left;
    else
    result = 0;
    }
    else if(temp < 27)
    result = pre_left + pre_right;
    else
    result = pre_right;
    pre_left = pre_right;
    pre_right = result;
    pre_char = s[i];
    }
    return result;
    }

    };


Log in to reply
 

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