A message containing letters from A-Z is being encoded to numbers using the following
'A' -> 1
'B' -> 2
...
'Z' -> 26
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.
// O(n) time, O(1) space
public class Solution {
    public int numDecodings(String s) {
        if(s.length() == 0) return 0;
        // i is decided by i+1, i+2
        int pre = 27, digit, first = 1, second = 1, res = 0;
        for(int i=s.length() -1; i>=0; i--) {
            digit = s.charAt(i) - '0';
            if(digit == 0) res = 0;
            else res = first + (digit*10 + pre <= 26 ? second : 0);
            second = first; first = res; pre = digit;
        }
        
        return res;
    }
}
/*  O(n) time, substring takes O(n), O(n) space
public class Solution {
    public int numDecodings(String s) {
        int n = s.length();
        if(n == 0) return 0;
        int[] memo = new int[n+1];  // ways to decode after this position
        memo[n] = 1;                // nothing to decode
        memo[n-1] = s.charAt(n-1) == '0' ? 0 : 1;
        
        for(int i=n-2; i>=0; i--) {
            if(s.charAt(i) == '0') continue;
            memo[i] = (Integer.parseInt(s.substring(i, i+2)) <= 26) ? memo[i+1] + memo[i+2] : memo[i+1];  
        }
        
        return memo[0];
    }
}
*/

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。