class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s.size() == 0 || s[0] == '0')
{
return 0;
}
int cntPre = 1;
int cnt = 1;
for (size_t i = 1; i < s.size(); ++i)
{
int tmp = cnt;
bool isCode = check(s[i - 1], s[i]);
if (s[i] != '0')
{
cnt = isCode ? cnt + cntPre : cnt;
}
else if (isCode)
{
cnt = cntPre;
}
else
{
cnt = 0;
break;
}
cntPre = tmp;
}
return cnt;
}
bool check(char ch1, char ch2)
{
return ch1 == '1' || (ch1 == '2' && ch2 <= '6');
}
};
LeetCode-Decode Ways
最新推荐文章于 2024-08-19 11:12:00 发布