My simple DP Solution in C, 0ms


  • 1
    P
    int isTwoValid(char first, char second) {
        int ret = 0;
        if(first=='1') ret++;
        else if(first=='2' && second<='6') ret++;
        return ret;
    }
    
    int isOneValid(char c) {
        return c > '0' ? 1 : 0;
    }
    
    int numDecodings(char* s) {
        int len = strlen(s);
        if(len==0) return 0;
        if(len==1) return isOneValid(s[0]);
        int f = 0, f1 = 1, f2 = isOneValid(s[0]);
        for(int i=1; i<len; i++) {
            f = isOneValid(s[i]) * f2 + isTwoValid(s[i-1], s[i]) * f1;
            f1 = f2;
            f2 = f;
        }
        return f;
    }

Log in to reply
 

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