Decode ways #91 Leetcode Problem #Leetcodeseries

1–2 minutes

read

Problem name: Decode ways

Problem statement:

A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "111" can have each of its "1"s be mapped into 'A's to make "AAA", or it could be mapped to "11" and "1" ('K' and 'A' respectively) to make "KA". Note that "06" cannot be mapped into 'F' since "6" is different from "06".

Given a non-empty string num containing only digits, return the number of ways to decode it.

The answer is guaranteed to fit in a 32-bit integer.

Example 1:

Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Solution:

class Solution {
public:
    int numDecodings(string s) {
        if(s.size()== 0){
            return 0;
        }
        if(s[0] == '0'){
            return 0;
        }
        if(s.size() == 1){
            return 1;
        }
        
        int val1 = 1;
        int val2 = 1;
        
        for(int i=1;i<s.size();i++){
            int first = s[i] - '0';
            int second = (s[i-1] - '0')*10 + first;
            
            int val = 0;
            if(first >= 1){
                val+=val2;
            }
            if(second>=10 && second<=26){
                val+=val1;
            }
            val1 = val2;
            val2 = val;
        }
        
        return val2;
    }
};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Decode Ways.Memory Usage: 6.3 MB, less than 87.42% of C++ online submissions for Decode Ways.

Leave a comment