File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ //
2+ // 91. Decode Ways
3+ // https://leetcode.com/problems/decode-ways/description/
4+ // Dale-Study
5+ //
6+ // Created by WhiteHyun on 2024/07/14.
7+ //
8+
9+ class Solution {
10+
11+ // dp
12+ func numDecodings( _ s: String ) -> Int {
13+ var ( current, previous) = ( 1 , 0 )
14+ let array = s. compactMap { Int ( String ( $0) ) }
15+ for index in array. indices. reversed ( ) {
16+ if array [ index] == 0 {
17+ ( current, previous) = ( 0 , current)
18+ } else if index + 1 < array. count, array [ index] * 10 + array[ index + 1 ] <= 26 {
19+ ( current, previous) = ( current + previous, current)
20+ } else {
21+ previous = current
22+ }
23+ }
24+
25+ return current
26+ }
27+
28+ // Memoization
29+ func numDecodingsUsingMemoization( _ s: String ) -> Int {
30+ let messages = s. compactMap { Int ( String ( $0) ) }
31+ var cache : [ Int : Int ] = [ s. count: 1 ]
32+
33+ func dfs( _ index: Int ) -> Int {
34+ if let cached = cache [ index] {
35+ return cached
36+ }
37+
38+ if messages [ index] == 0 {
39+ cache [ index] = 0
40+ } else if index + 1 < s. count && messages [ index] * 10 + messages[ index + 1 ] < 27 {
41+ cache [ index] = dfs ( index + 1 ) + dfs( index + 2 )
42+ } else {
43+ cache [ index] = dfs ( index + 1 )
44+ }
45+ return cache [ index] !
46+ }
47+
48+ return dfs ( 0 )
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments