第91题:解码问题

一. 问题描述

一条包含字母 A-Z 的消息通过以下方式进行了编码:

'A' -> 1

'B' -> 2

...

'Z' -> 26

给定一个只包含数字的非空字符串,请计算解码方法的总数。

示例 1:

输入: "12"

输出: 2

解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。

示例 2:

输入: "226"

输出: 3

解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。

二. 解题思路

本题思路:(本题跟动态规划其实关系不大,最烦人的是边界的处理,碰到各种智障情况)采用动态规划进行求解,找到状态转移函数f(n)=f(n-1)+f(n-2)

步骤一:本题主要是边界问题,出现00 ,01等一系列不正确数字,进行判断,然后进行相应输出。

步骤二:通过遍历字符串s,得到最后f(n-1)和f(n-2)。

步骤三:相加得到f(n)的总数,然后输出。

三. 执行结果

执行用时 :4 ms, 在所有 java 提交中击败了35.41%的用户

内存消耗 :36.1 MB, 在所有 java 提交中击败了27.80%的用户

四. Java代码

class Solution {
    public int numDecodings(String s) {
       int first=1;   
        int second=0;
        if(s.length()==1&&s.charAt(0)!='0')
        {
            return first;
        }else if((s.length()<=0&&s!=null)||s.charAt(0)=='0')
        {
            return 0;
        }
        
        String m=""+s.charAt(0)+s.charAt(1)+"";
         if((s.charAt(0)=='0'&&s.charAt(1)=='0')||(s.charAt(1)=='0'&&Integer.parseInt(m)>26))
        {
            return 0;
        }
        if(Integer.parseInt(m)>26||s.charAt(1)=='0')
        {
            second=1;
        }else
        {
            second=2;
        }
        
        for(int i=2;i<s.length();i++)
        {
        String l=""+s.charAt(i-1)+s.charAt(i)+"";
         if((s.charAt(i-1)=='0'&&s.charAt(i)=='0')||(s.charAt(i)=='0'&&Integer.parseInt(l)>26))
         {
             return 0;
         }
         if(Integer.parseInt(l)>26||s.charAt(i-1)=='0')
         {
             
             first=second;
             second=second;
         }else if(Integer.parseInt(l)<=26&&s.charAt(i)!='0')
         {
             int temp=first;
             first=second;
             second=temp+second;
         }else
         {
             second=first;
             first=0;
         }
        }
        return second;
    }
}
原文地址:https://www.cnblogs.com/xiaobaidashu/p/11758491.html