[LeetCode] 91. Decode Ways
A message containing letters from
A-Z
is being encoded to numbers using the following mapping:'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message
Given encoded message
"12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding
"12"
is 2.
Thought process:
Dynamic programming.
- Sub-problem: determine the total number of ways to decode a sub-string.
- Function: iterate through the string from back to beginning.
- If s[i] == 0: continue. I can keep f[i] at default value 0 because it would be correct even if s's first character is 0 (return f[0] = 0).
- Else:
- If s[i, i + 2] <= 26, f[i] = f[i + 1] + f[i + 2].
- Else, f[i] = f[i + 1].
- Initialization: f[s.length()] = 1. f[s.length() - 1] = 1 if s's last character is not 0.
- Answer: f[0].
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public int numDecodings(String s) { int len = s.length(); if (len == 0) { return 0; } int[] f = new int[len + 1]; f[len] = 1; f[len - 1] = s.charAt(len - 1) == '0' ? 0 : 1; for (int i = len - 2; i >= 0; i--) { if (s.charAt(i) == '0') { continue; } if (Integer.parseInt(s.substring(i, i + 2)) <= 26) { f[i] = f[i + 1] + f[i + 2]; } else { f[i] = f[i + 1]; } } return f[0]; } } |
Time complexity: O(n).
WtrahidQconsa Fabian Byrd https://marketplace.visualstudio.com/items?itemName=lacsipilba.Descargar-Antonball-Deluxe-gratuita-2021
ReplyDeletehayralala
Nalinmen-dzu_Sioux Falls Greg Stepp Download crack
ReplyDeletenolofilne
credviu0edwa-Jacksonville Brenda Porter click here
ReplyDeleteclick here
link
link
inylglovin