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.

一维动态规划

f[i] = f(i-1) s[i]>=’1’ && s[i]<=’9’
+ f(i-2) i>0 && s[i-1][i] >=‘10’ && s[i-1][i] <=’26’

可以优化空间复杂度到 O(1)


public class Solution {
    public int numDecodings(String s) {
        int len = s.length();
        if(len == 0){
            return 0;
        }
        
        
        int [] ways = new int[3];
        ways[0] = 1; 
        ways[1] = 1;
        for(int i = 0; i= '1' && ci <='9'){
                ways[(i+2)%3] = ways[(i+1)%3];
            }else{
                ways[(i+2)%3] = 0;
            }
            if(i==0){
                continue;
            }
            
            char ci1 = s.charAt(i-1);
            if(ci1 == '1'&& ci>='0' && ci<='9' ||
                ci1 == '2' && ci>= '0' && ci<= '6'){
                ways[(i+2)%3] += ways[i%3];
            }
        }
        return ways[(len+1)%3];
    }
}

你可能感兴趣的:(91. Decode Ways)