91. Decode Ways
message containing letters from A-Z is being encoded to numbers using the following mapping:
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Input: “12”
Output: 2
Explanation: It could be decoded as “AB” (1 2) or “L” (12).
这道题的判断条件较为复杂,要仔细思考。
class Solution {
public int numDecodings(String s) {
int count = s.charAt(0) == '0' ? 0 : 1;
int pre = 1, tmp = 0;
for (int i = 1; i < s.length() && count != 0; i++) {
tmp = count;
if (s.charAt(i - 1) == '1' || s.charAt(i - 1) == '2' && s.charAt(i) <= '6') {
if (s.charAt(i) == '0')
count = pre;
else
count += pre;
}else if(s.charAt(i)=='0'){
count=0;
}
pre = tmp;
}
return count;
}
}