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)