本文主要是介绍LeetCode *** 91. Decode Ways,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
分析:
代码:
class Solution {
public:int numDecodings(string s) {int len = s.length(), ppre = 1, pre = 1, res = 0;if (len == 0 || s[0] == '0')return 0;if (len == 1)return 1;for (int i = 1; i<len; ++i) {if (isValid(s[i]) && isValid(s[i - 1], s[i]))res = ppre + pre;if (isValid(s[i]) && !isValid(s[i - 1], s[i]))res = pre;if (!isValid(s[i]) && isValid(s[i - 1], s[i]))res = ppre;if (!isValid(s[i]) && !isValid(s[i - 1], s[i]))return 0;ppre = pre;pre = res;res = 0;}return pre;}bool isValid(char a, char b) {return a == '1' || (a == '2'&&b <= '6');}bool isValid(char c) {return c != '0';}
};
这篇关于LeetCode *** 91. Decode Ways的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!