[LeetCode] Decode Ways

91. Decode Ways

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 grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, “11106” can be mapped into:

  • “AAJF” with the grouping (1 1 10 6)
  • “KJF” with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because “06” cannot be mapped into ‘F’ since “6” is different from “06”.

Given a string s containing only digits, return the number of ways to decode it.

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

  • new solution update 2022.02.10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int dp[101];
int dfs(string& s, int pos) {
if(s.length() <= pos) return 1;
if(dp[pos] != -1) return dp[pos];
if(s[pos] == '0') return dp[pos] = 0;
dp[pos] = dfs(s, pos + 1);
if(pos + 1 != s.length()) {
int sum = (s[pos]&0b1111)*10 + (s[pos+1]&0b1111);
if(1 <= sum and sum <= 26)
dp[pos] += dfs(s, pos + 2);
}
return dp[pos];
}
public:
int numDecodings(string s) {
memset(dp,-1,sizeof(dp));
return dfs(s, 0);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private:
unordered_map<string, int> strings;
private:
bool canDecoded(int digit) {
return 1 <= digit && digit <= 26;
}

int recursive(string plain) {
if(plain.length() == 0) {
return 1;
}

auto stringValue = strings.find(plain);
if(stringValue != strings.end()) {
return stringValue->second;
}

int ret = 0;
for(int i = 1; i <= 2; i++) {
if(plain.length() >= i && plain[0] != '0' && canDecoded(stoi(plain.substr(0,i)))) {
ret += recursive(plain.substr(i));
}
}
strings[plain] = ret;
return ret;
}
public:
int numDecodings(string s) {
return recursive(s);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/27/PS/LeetCode/decode-ways/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.