From a563e94d33c76f39626f60ae387a4c0953d9a0fc Mon Sep 17 00:00:00 2001 From: prasanna Date: Wed, 26 Nov 2025 14:47:35 +0530 Subject: [PATCH] Implement numDecodings function for decoding ways --- decode.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 decode.c diff --git a/decode.c b/decode.c new file mode 100644 index 0000000..c63ee84 --- /dev/null +++ b/decode.c @@ -0,0 +1,32 @@ +int numDecodings(char *s) { + int n = strlen(s); + if (n == 0 || s[0] == '0') + return 0; + + int dp_prev2 = 1; // dp[i-2] + int dp_prev1 = 1; // dp[i-1] + + for (int i = 1; i < n; i++) { + int dp_current = 0; + + // Case 1: Single digit decode (must not be '0') + if (s[i] != '0') { + dp_current += dp_prev1; + } + + // Case 2: Two-digit decode (10 to 26) + int twoDigit = (s[i - 1] - '0') * 10 + (s[i] - '0'); + if (twoDigit >= 10 && twoDigit <= 26) { + dp_current += dp_prev2; + } + + // If no valid decoding + if (dp_current == 0) + return 0; + + dp_prev2 = dp_prev1; + dp_prev1 = dp_current; + } + + return dp_prev1; +}