Skip to content

Commit 32a53ec

Browse files
committed
decode_ways solved
1 parent 7285a5c commit 32a53ec

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

decode-ways/kut7728.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
///정수 문자열 암호문을 습득했고, 1 -> A, 2 -> B ... 25 -> Y, 26 -> Z 이런식으로 해독됨
2+
///정수 문자열을 어떻게 끊느냐에 따라 해독이 다르게 된다는 점을 고려해서
3+
///해독 될수 있는 모든 경우의 수를 반환하라, 해독이 안된다면 0을 반환하라
4+
///
5+
///EX) s = "12"
6+
///output : 2 -> (1 2) "AB" or (12) "L"
7+
8+
9+
class Solution {
10+
func numDecodings(_ s: String) -> Int {
11+
let arr = Array(s)
12+
var memo: [Int:Int] = [arr.count:1]
13+
14+
func dfs(_ start: Int) -> Int {
15+
if let result = memo[start] {
16+
return result
17+
}
18+
19+
20+
if arr[start] == "0" {
21+
memo[start] = 0
22+
} else if start + 1 < arr.count, Int(String(arr[start...start+1]))! <= 26 {
23+
memo[start] = dfs(start+1) + dfs(start+2)
24+
} else {
25+
memo[start] = dfs(start + 1)
26+
}
27+
28+
return memo[start]!
29+
}
30+
31+
return dfs(0)
32+
}
33+
}

0 commit comments

Comments
 (0)