From d3bc57de1822225a541a0981d0684d42cb3709f3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 25 Dec 2023 15:39:19 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=E2=80=9C91.=20Decode=20Ways?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/decode-ways.java | 51 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 java/decode-ways.java diff --git a/java/decode-ways.java b/java/decode-ways.java new file mode 100644 index 0000000..3bb9f71 --- /dev/null +++ b/java/decode-ways.java @@ -0,0 +1,51 @@ +class Solution { + private static final int EMPTY = -1; + + private static int charToDigit(String s, int i) { + return s.charAt(i) - '0'; + } + + private int numDecodings(String s, int[] dp, int i) { + // out of bounds + if (i < 0 || i > s.length()) { + return 0; + } + + // final digit + if (i == s.length()) { + return 1; + } + + // starting with 0, not allowed + if (s.charAt(i) == '0') { + return 0; + } + + // solution has been already precomputed + if (dp[i] != EMPTY) { + return dp[i]; + } + + // taking just one digit + int result = numDecodings(s, dp, i + 1); + + // taking two digits + if (i + 1 < s.length() && charToDigit(s, i) * 10 + charToDigit(s, i + 1) <= 26) { + result += numDecodings(s, dp, i + 2); + } + + // save and return + dp[i] = result; + return result; + } + + public int numDecodings(String s) { + int[] dp = new int[s.length()]; + for (int i = 0; i < dp.length; ++i) { + dp[i] = EMPTY; + } + + return numDecodings(s, dp, 0); + } +} +