forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneverlish.go
59 lines (45 loc) ยท 924 Bytes
/
neverlish.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// ์๊ฐ๋ณต์ก๋: O(n)
// ๊ณต๊ฐ๋ณต์ก๋: O(n)
package main
import (
"testing"
)
func TestNumDecodings(t *testing.T) {
test1 := "12"
result1 := numDecodings(test1)
if result1 != 2 {
t.Errorf("Expected 2, got %d", result1)
}
test2 := "226"
result2 := numDecodings(test2)
if result2 != 3 {
t.Errorf("Expected 3, got %d", result2)
}
test3 := "0"
result3 := numDecodings(test3)
if result3 != 0 {
t.Errorf("Expected 0, got %d", result3)
}
test4 := "06"
result4 := numDecodings(test4)
if result4 != 0 {
t.Errorf("Expected 0, got %d", result4)
}
}
func numDecodings(s string) int {
dp := make([]int, len(s)+1)
dp[0] = 1
for i := 1; i <= len(s); i++ {
curBefore1 := s[i-1]
if curBefore1 != '0' {
dp[i] += dp[i-1]
}
if i > 1 {
curBefore2 := s[i-2]
if curBefore2 != '0' && (curBefore2-'0')*10+(curBefore1-'0') <= 26 {
dp[i] += dp[i-2]
}
}
}
return dp[len(s)]
}