Review an answer - Decode Ways

前端 未结 7 1247
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 19:36

I\'m trying to solve a question and my question here is why doesn\'t my solution work?. Here\'s the question and below\'s the answer.

Question taken fr

7条回答
  •  深忆病人
    2021-01-31 20:38

    My solution is based on the idea that the arrangement of items(char/digit) within a particular substring is completely independent of the same within a different substring. So we need to multiply each of those independent ways to get the total number of ways.

    // nc is the number of consecutive 1's or 2's in a substring.
    // Returns the number of ways these can be arranged  within 
    // themselves to a valid expr.
    int ways(int nc){
        int n = pow(2, (nc/2)); //this part can be memorized using map for optimization
        int m = n;
        if (nc%2) {
            m *= 2;
        }
        return n + m - 1;  
    }
    bool validTens(string A, int i){
        return (A[i] == '1' || (A[i] == '2' && A[i+1] <= '6'));
    }
    int numDecodings(string A) {
        int ans = 1;
        int nc;
    
        if ((A.length() == 0)||(A[0] == '0')) return 0;
    
        for(int i = 1; i < A.length();i++){
            if(A[i] == '0' && validTens(A, i-1) == false) return 0; //invalid string
            while(i < A.length() && validTens(A, i-1)) {
                if(A[i] == '0'){
                    //think of '110' or '1210', the last two digits must be together
                    if(nc > 0) nc--;  
                }
                else nc++;
                i++;
            }
            ans *= ways(nc);
            nc = 0;
        }
        return ans;
    }
    

提交回复
热议问题