【ALGO】Leetcode 91.解碼方法
題面
原題連結
一條包含字母 A-Z 的訊息通過以下方式進行了編碼:
'A' -> 1
'B' -> 2
...
'Z' -> 26
給定一個只包含數字的非空字串,請計算解碼方法的總數。
題目資料保證答案肯定是一個 32 位的整數。
解析
使用動態規劃演算法求解,定義
f
[
i
]
f[i]
f[i]表示由前
i
i
i個字元可以解碼回去的字串集合,考慮1位解碼和兩位解碼的情況,轉移方程為
f
[
i
]
=
f
[
i
]
+
f
[
i
−
1
]
f
[
i
]
=
f
[
i
]
+
f
[
i
−
2
]
if
(
s
[
i
−
1
]
−
′
0
′
)
∗
10
+
(
s
[
i
]
−
′
0
′
)
∈
[
10
,
26
]
f[i]=f[i]+f[i-1]\\ f[i]=f[i]+f[i-2] \quad \text{if} (s[i-1]-'0')*10+(s[i]-'0')\in[10, 26]
f[i]=f[i]+f[i−1]f[i]=f[i]+f[i−2]if(s[i−1]−′0′)∗10+(s[i]−′0′)∈[10,26]
AC程式碼
class Solution {
public:
int numDecodings(string s) {
int n=s.size();
s = ' '+s;
vector<int> f(n+1);
f[0]=1;
for(int i=1; i<=n; ++i){
if(s[i]>='1' && s[i]<='9') f[i]+=f[i-1];
if(i>1){
int t=(s[i-1]-'0')*10+s[i]-'0';
if(t>=10 && t<=26) f[i]+=f[i-2];
}
}
return f[n];
}
};
相關文章
- 微軟面試題: LeetCode 91. 解碼方法 出現次數:3微軟面試題LeetCode
- 【ALGO】Leetcode 85.最大矩形GoLeetCode
- 【ALGO】Leetcode 97.交錯字串GoLeetCode字串
- LeetCode_91.解碼方法LeetCode
- 《STL原始碼剖析》 -- stl_algo.h原始碼Go
- LeetCode-091-解碼方法LeetCode
- 【ALGO】Leetcode 98.驗證二叉搜尋樹GoLeetCode
- LeetCode 394 字串解碼LeetCode字串
- [Leetcode]394.字串解碼LeetCode字串
- 用指令碼整理Leetcode題解指令碼LeetCode
- LintCode 解碼方法
- putty亂碼解決方法
- 【leetcode】leetcode22括號生成通過程式碼及題解LeetCode
- Google 面試題 | 解碼方法2Go面試題
- ALGO-201 大等於n的最小完全平方數Go
- Redux原始碼createStore解讀常用方法Redux原始碼
- jQuery的extend方法原始碼解讀jQuery原始碼
- 忘記INTERNAL密碼解決方法密碼
- secureCRT顯示亂碼解決方法Securecrt
- MYSQL亂碼問題解決方法MySql
- [Java] 藍橋杯ALGO-117 演算法訓練 友好數JavaGo演算法
- javaweb中中文亂碼解決方法總結之response和request解決方法JavaWeb
- [leetcode 題解] 849LeetCode
- Leetcode 全套題解LeetCode
- 「LeetCode」全部題解LeetCode
- java中亂碼問題解決方法Java
- mongodb密碼特殊字元的解決方法MongoDB密碼字元
- Vue 原始碼解讀(6)—— 例項方法Vue原始碼
- Mysql忘記密碼解決方法凹MySql密碼
- 程式碼混淆的原理和方法詳解
- SUSE root密碼忘記解決方法密碼
- mysql與jsp亂碼解決方法MySqlJS
- Linux 忘記密碼解決方法Linux密碼
- 九種解決亂碼方法總結
- Python3內建模組之json編碼解碼方法講解PythonJSON
- centos7 vim中文亂碼解決方法CentOS
- toad 中文顯示亂碼解決方法
- MySQL 忘記root密碼的解決方法MySql密碼