diff --git a/kotlin/0091-decode-ways.kt b/kotlin/0091-decode-ways.kt index cad2fd1e5..96d315635 100644 --- a/kotlin/0091-decode-ways.kt +++ b/kotlin/0091-decode-ways.kt @@ -1,22 +1,22 @@ class Solution { - fun numDecodings(s: String): Int { - val n = s.length - val dp = IntArray(n+1) - dp[0] = 1 - dp[1] = if (s[0] == '0') 0 else 1 - - for (i in 2..n) { - val curr = s[i-1] - '0' - val prev = s[i-2] - '0' - val num = 10*prev + curr - - if (curr > 0) - dp[i] += dp[i-1] - - if (num >= 10 && num <= 26) - dp[i] += dp[i-2] + // Time : O(n) | Space : O(n) + fun numDecodings(string: String): Int { + if (string.length == 1) return if (string.last() != '0') 1 else 0 + // dp array + val numberOfDecodings = IntArray(string.length + 1).apply { + this[lastIndex - 1] = if (string.last() == '0') 0 else 1 + this[lastIndex] = if ("${string[string.lastIndex - 1]}${string[string.lastIndex]}".toInt() <= 26) 1 else 0 } - - return dp[n] + for (i in (string.lastIndex - 1) downTo 0) { + if (string[i] == '0') { + numberOfDecodings[i] = 0 + continue + } + numberOfDecodings[i] += numberOfDecodings[i + 1] + numberOfDecodings[i] += numberOfDecodings[i + 2].takeIf { + (string[i] == '1' && string[i + 1] in '0'..'9') || (string[i] == '2' && string[i + 1] in '0'..'6') + } ?: 0 + } + return numberOfDecodings[0] } } \ No newline at end of file