From 38875b19fb8938d22c24b87f0839cbc45bec418a Mon Sep 17 00:00:00 2001 From: novahe Date: Mon, 24 May 2021 23:16:08 +0800 Subject: [PATCH] update 91 --- leetcode/0091.Decode-Ways/91. Decode Ways.go | 25 +++++-------------- .../ChapterFour/0001~0099/0091.Decode-Ways.md | 25 +++++-------------- 2 files changed, 12 insertions(+), 38 deletions(-) diff --git a/leetcode/0091.Decode-Ways/91. Decode Ways.go b/leetcode/0091.Decode-Ways/91. Decode Ways.go index 35a97845..6746cdc4 100644 --- a/leetcode/0091.Decode-Ways/91. Decode Ways.go +++ b/leetcode/0091.Decode-Ways/91. Decode Ways.go @@ -1,29 +1,16 @@ package leetcode -import ( - "strconv" -) - func numDecodings(s string) int { - if len(s) == 0 { - return 0 - } - dp := make([]int, len(s)+1) + n := len(s) + dp := make([]int, n+1) dp[0] = 1 - if s[:1] == "0" { - dp[1] = 0 - } else { - dp[1] = 1 - } - for i := 2; i <= len(s); i++ { - lastNum, _ := strconv.Atoi(s[i-1 : i]) - if lastNum >= 1 && lastNum <= 9 { + for i := 1; i <= n; i++ { + if s[i-1] != '0' { dp[i] += dp[i-1] } - lastNum, _ = strconv.Atoi(s[i-2 : i]) - if lastNum >= 10 && lastNum <= 26 { + if i > 1 && s[i-2] != '0' && (s[i-2]-'0')*10+(s[i-1]-'0') <= 26 { dp[i] += dp[i-2] } } - return dp[len(s)] + return dp[n] } diff --git a/website/content/ChapterFour/0001~0099/0091.Decode-Ways.md b/website/content/ChapterFour/0001~0099/0091.Decode-Ways.md index 6bb4b168..7ac98506 100755 --- a/website/content/ChapterFour/0001~0099/0091.Decode-Ways.md +++ b/website/content/ChapterFour/0001~0099/0091.Decode-Ways.md @@ -51,32 +51,19 @@ Given a **non-empty** string containing only digits, determine the total numbe package leetcode -import ( - "strconv" -) - func numDecodings(s string) int { - if len(s) == 0 { - return 0 - } - dp := make([]int, len(s)+1) + n := len(s) + dp := make([]int, n+1) dp[0] = 1 - if s[:1] == "0" { - dp[1] = 0 - } else { - dp[1] = 1 - } - for i := 2; i <= len(s); i++ { - lastNum, _ := strconv.Atoi(s[i-1 : i]) - if lastNum >= 1 && lastNum <= 9 { + for i := 1; i <= n; i++ { + if s[i-1] != '0' { dp[i] += dp[i-1] } - lastNum, _ = strconv.Atoi(s[i-2 : i]) - if lastNum >= 10 && lastNum <= 26 { + if i > 1 && s[i-2] != '0' && (s[i-2]-'0')*10+(s[i-1]-'0') <= 26 { dp[i] += dp[i-2] } } - return dp[len(s)] + return dp[n] } ```