码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 91. Decode Ways

时间:2019-12-16 10:17:31      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:div   sage   cas   class   let   integer   map   ret   only   

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

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

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

class Solution {
    public int numDecodings(String s) {
        int[] arr = new int[s.length() + 1];
        arr[0] = 1;
        // for case of ‘0‘;
        arr[1] = s.charAt(0) == ‘0‘ ? 0 : 1;
        for (int i = 2; i <= s.length(); i++) {
            int preOne = Integer.valueOf(s.substring(i - 1, i));
            int preTwo = Integer.valueOf(s.substring(i - 2, i));
            if (preOne >= 1 && preOne <= 9) {
                arr[i] += arr[i - 1];
            }
            if (preTwo >= 10 && preTwo <= 26) {
                arr[i] += arr[i - 2];
            }
        }
        return arr[s.length()];
    }
}

[LC] 91. Decode Ways

标签:div   sage   cas   class   let   integer   map   ret   only   

原文地址:https://www.cnblogs.com/xuanlu/p/12047192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!