91. Decode Ways

Medium

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

FB的高頻題,老師以climbing stairs引出來(lái)的,會(huì)了就比較簡(jiǎn)單。有幾個(gè)地方要注意以下:

  • 方便表達(dá),用dp[i]表示到達(dá)所給串的第i個(gè)字符時(shí),一共有的decode的方法, dp[0]表達(dá)的是字符串是空的時(shí)候可以decode的方法數(shù)(1種而不是0種),而不是達(dá)到s.charAt(0)時(shí)候的方法數(shù)
  • 判斷s.charAt(0) == 0?, 如果等于,其實(shí)是不可能出現(xiàn)的情況,方法數(shù)為零,也可以直接返回0了。
  • for循環(huán)從i = 2開(kāi)始,因?yàn)槲覀儚膁p[2]開(kāi)始求。 dp[2]表達(dá)的是到達(dá)第二個(gè)字符串一共能decode的方法總數(shù)。那么我們就需要看當(dāng)前字符串構(gòu)成的一位數(shù)和前一個(gè)字符串加上當(dāng)前字符串構(gòu)成的二位數(shù)即s[1], s[0,1], 也就是s.substring(i - 1, i)和s.substring(i - 2, i), 分別看前者是不是在[1, 9]范圍里,后者是不是在[10,26]范圍里,如果是,就dp[i] += dp[i - 1]或dp[i] += dp[i - 2].
class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = s.charAt(0) == '0' ? 0 : 1;
        for (int i = 2; i <= s.length(); i++){
            int prevOne = Integer.valueOf(s.substring(i - 1, i));
            int prevTwo = Integer.valueOf(s.substring(i - 2, i));
            if (prevOne > 0 && prevOne <= 9){
                dp[i] += dp[i - 1];
            }
            if (prevTwo >= 10 && prevTwo <= 26){
                dp[i] += dp[i - 2];
            }
        }
        return dp[n];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容