leetcode91. 解码方法
生活随笔
收集整理的這篇文章主要介紹了
leetcode91. 解码方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一條包含字母 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];} }總結
以上是生活随笔為你收集整理的leetcode91. 解码方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到别人建房子是什么意思
- 下一篇: 梦到初恋向自己求婚是什么意思