classSolution { public: intnumDecodings(string s){ int n = s.size(); // a = f[i-2], b = f[i-1], c = f[i] int a = 0, b = 1, c; for (int i = 1; i <= n; ++i) { c = 0; if (s[i - 1] != '0') { c += b; } if (i > 1 && s[i - 2] != '0' && ((s[i - 2] - '0') * 10 + (s[i - 1] - '0') <= 26)) { c += a; } tie(a, b) = {b, c}; } return c; } };
[sol12-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintnumDecodings(String s) { intn= s.length(); // a = f[i-2], b = f[i-1], c=f[i] inta=0, b = 1, c = 0; for (inti=1; i <= n; ++i) { c = 0; if (s.charAt(i - 1) != '0') { c += b; } if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0') <= 26)) { c += a; } a = b; b = c; } return c; } }
[sol12-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defnumDecodings(self, s: str) -> int: n = len(s) # a = f[i-2], b = f[i-1], c = f[i] a, b, c = 0, 1, 0 for i inrange(1, n + 1): c = 0 if s[i - 1] != '0': c += b if i > 1and s[i - 2] != '0'andint(s[i-2:i]) <= 26: c += a a, b = b, c return c
[sol12-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var numDecodings = function(s) { const n = s.length; // a = f[i-2], b = f[i-1], c = f[i] let a = 0, b = 1, c = 0; for (let i = 1; i <= n; ++i) { c = 0; if (s[i - 1] !== '0') { c += b; } if (i > 1 && s[i - 2] != '0' && ((s[i - 2] - '0') * 10 + (s[i - 1] - '0') <= 26)) { c += a; } a = b; b = c; } return c; };
[sol12-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcnumDecodings(s string)int { n := len(s) // a = f[i-2], b = f[i-1], c = f[i] a, b, c := 0, 1, 0 for i := 1; i <= n; i++ { c = 0 if s[i-1] != '0' { c += b } if i > 1 && s[i-2] != '0' && ((s[i-2]-'0')*10+(s[i-1]-'0') <= 26) { c += a } a, b = b, c } return c }
[sol12-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
intnumDecodings(char* s) { int n = strlen(s); // a = f[i-2], b = f[i-1], c = f[i] int a = 0, b = 1, c; for (int i = 1; i <= n; ++i) { c = 0; if (s[i - 1] != '0') { c += b; } if (i > 1 && s[i - 2] != '0' && ((s[i - 2] - '0') * 10 + (s[i - 1] - '0') <= 26)) { c += a; } a = b, b = c; } return c; }