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

Decode Ways

时间:2019-12-21 22:40:11      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:output   script   字符串   param   public   方案   determine   coding   its   

Description

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.

Example

Example 1:

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

Example 2:

Input: "10"
Output: 1
思路:

动态规划.

设定状态: f[i] 表示字符串前i位有多少种解码方案

状态转移方程:

初始化 f 数组为 0
若字符串中 s[i] 表示的阿拉伯数字在 1~9 范围内, f[i] += f[i-1]
若s[i-1]和s[i]连起来表示的数字在 10~26 范围内, f[i] += f[i-2] (若i==1, 则f[i] += 1)

边界: f[0] = 1

特判:

  1. 如果字符串以 ‘0‘ 开头, 则直接返回0.
  2. 如果运算中发现 f[i] == 0, 则说明此处无法解码, 同样直接返回0.
    public class Solution {
        /**
         * @param s: a string,  encoded message
         * @return: an integer, the number of ways decoding
         */
        public int numDecodings(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            int[] nums = new int[s.length() + 1];
            nums[0] = 1;
            nums[1] = s.charAt(0) != ‘0‘ ? 1 : 0;
            for (int i = 2; i <= s.length(); i++) {
                if (s.charAt(i - 1) != ‘0‘) {
                    nums[i] = nums[i - 1];
                }
                
                int twoDigits = (s.charAt(i - 2) - ‘0‘) * 10 + s.charAt(i - 1) - ‘0‘;
                if (twoDigits >= 10 && twoDigits <= 26) {
                    nums[i] += nums[i - 2];
                }
            }
            return nums[s.length()];
        }
    }
    

      

Decode Ways

标签:output   script   字符串   param   public   方案   determine   coding   its   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078207.html

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