Skip to content

Commit c15e4b0

Browse files
committed
Add problem 91 - Decode Ways
1 parent 0e862dc commit c15e4b0

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package dynamic_programming
2+
3+
func DecodeWays(s string) int {
4+
// Special case
5+
if len(s) == 0 {
6+
return 0
7+
}
8+
// Length of the string and previous and current pointers
9+
n, previous, current := len(s), 1, 0
10+
// Process the string from right to left
11+
for i := n - 1; i >= 0; i-- {
12+
temp := 0
13+
if s[i] != '0' {
14+
temp = previous
15+
}
16+
if i < n-1 && (s[i] == '1' || s[i] == '2' && s[i+1] < '7') {
17+
temp += current
18+
}
19+
current = previous
20+
previous = temp
21+
}
22+
return previous
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package dynamic_programming_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/dynamic_programming"
7+
)
8+
9+
func TestNumDecodings(t *testing.T) {
10+
// Test case for null string
11+
if result := dynamic_programming.DecodeWays(""); result != 0 {
12+
t.Errorf("Expected 0, got %d", result)
13+
}
14+
15+
// Test case for string with a single character
16+
if result := dynamic_programming.DecodeWays("1"); result != 1 {
17+
t.Errorf("Expected 1, got %d", result)
18+
}
19+
20+
// Test case for string with multiple characters
21+
if result := dynamic_programming.DecodeWays("12"); result != 2 {
22+
t.Errorf("Expected 2, got %d", result)
23+
}
24+
25+
// Test case for string with leading zeros
26+
if result := dynamic_programming.DecodeWays("012"); result != 0 {
27+
t.Errorf("Expected 0, got %d", result)
28+
}
29+
30+
// Test case for string with multiple decoding possibilities
31+
if result := dynamic_programming.DecodeWays("226"); result != 3 {
32+
t.Errorf("Expected 3, got %d", result)
33+
}
34+
35+
// Test case for string with no valid decodings
36+
if result := dynamic_programming.DecodeWays("30"); result != 0 {
37+
t.Errorf("Expected 0, got %d", result)
38+
}
39+
40+
// Test case for string with multiple valid decodings
41+
if result := dynamic_programming.DecodeWays("11106"); result != 2 {
42+
t.Errorf("Expected 2, got %d", result)
43+
}
44+
}

0 commit comments

Comments
 (0)