easy to understand c++ solution


  • 0
    K
    bool isvalid(int p, string& s){
            if(s[p]>'0' && s[p]<='0'+9) return true;
            else return false;
        }
        bool isvalid(int p1, int p2, string& s){
            if(10*(s[p1]-'0')+s[p2]-'0'<=26 && s[p1]>'0') return true;
            else return false;
        }
        int numDecodings(string s) {
            if(s.empty()) return 0;
            if(s[0]=='0') return 0;
            int d0=1,d1=1,di=0;
            if(s.size()==1) return d0;
            for(int i=1; i<s.size(); i++){
                if(isvalid(i,s) && isvalid(i-1,i,s)){
                    di=d0+d1;
                }
                else if(isvalid(i,s)){
                    di=d1;
                }
                else if(isvalid(i-1,i,s)){
                    di=d0;
                }
                else{
                    di=0;
                    break;
                } 
                
                d0=d1;
                d1=di;
            }
            return di;
        }
    

Log in to reply
 

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