一条包含字母 A-Z 的消息通过以下方式进行了编码:
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: “12”
输出: 2
解释: 它可以解码为 “AB”(1 2)或者 “L”(12)。
代码
class Solution {int[] dp;public int numDecodings(String s) {int l=s.length();dp=new int[l];Arrays.fill(dp,-1);return getNumDecodings( s,0);}public int getNumDecodings(String s,int loc) {if(loc>=s.length()) return 1;if(dp[loc]!=-1) return dp[loc];//记忆化int o=0,t=0;if(loc+1<=s.length()&&Integer.parseInt(s.substring(loc,loc+1))>=1&&Integer.parseInt(s.substring(loc,loc+1))<=26)//分成1位数字或2位o=getNumDecodings(s,loc+1);if(loc+2<=s.length()&&Integer.parseInt(s.substring(loc,loc+2))>=10&&Integer.parseInt(s.substring(loc,loc+2))<=26)//判断当前分割字符串的合法性t=getNumDecodings(s,loc+2);dp[loc]=o+t;return dp[loc];}
}