Skip to content

Commit 16270f6

Browse files
author
Yi Gu
committed
[DP] Optimize code style for Decode Ways
1 parent 98daf52 commit 16270f6

File tree

1 file changed

+14
-20
lines changed

1 file changed

+14
-20
lines changed

DP/DecodeWays.swift

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,41 +8,35 @@
88

99
class DecodeWays {
1010
func numDecodings(_ s: String) -> Int {
11-
let chars = Array(s.characters), len = chars.count
12-
13-
guard len > 0 else {
14-
return 0
15-
}
16-
11+
let sChars = Array(s.characters), len = sChars.count
1712
var dp = Array(repeating: 0, count: len + 1)
1813
dp[0] = 1
19-
dp[1] = isValid(String(chars[0 ..< 1])) ? 1 : 0
20-
21-
guard len >= 2 else {
22-
return dp[len]
14+
15+
guard len >= 1 else {
16+
return 0
2317
}
2418

25-
for i in 2 ... len {
26-
if isValid(String(chars[i - 1 ..< i])) {
19+
for i in 1 ... len {
20+
if isValid(String(sChars[i - 1 ..< i])) {
2721
dp[i] += dp[i - 1]
2822
}
29-
if isValid(String(chars[i - 2 ..< i])) {
23+
if i >= 2 && isValid(String(sChars[i - 2 ..< i])) {
3024
dp[i] += dp[i - 2]
3125
}
3226
}
3327

3428
return dp[len]
3529
}
3630

37-
private func isValid(_ str: String) -> Bool {
38-
let chars = Array(str.characters)
39-
40-
if chars[0] == "0" {
31+
private func isValid(_ numStr: String) -> Bool {
32+
if Array(numStr.characters).first == "0" {
33+
return false
34+
}
35+
36+
guard let num = Int(numStr) else {
4137
return false
4238
}
4339

44-
let num = Int(str)!
45-
46-
return num > 0 && num <= 26
40+
return num >= 1 && num <= 26
4741
}
4842
}

0 commit comments

Comments
 (0)