Decode ways

https://leetcode.com/problems/decode-ways/

  • count[i] = count[i - 1] if s.charAt(i) is valid
  • or count[i] = count[i - 1] + count[i - 2] when s.charAt(i - 1) and s.charAt(i - 2) is valid.
public int numDecodings(String s) {
    //rule out corner case
     if (s.startsWith("0") || s.length() < 1) return 0;
     if (s.length() == 1) return 1;

     int[] count = new int[s.length()];
     count[0] = check(s.charAt(0));
     // check the first two characeters
     // if the second one itself is not valid, we just consider the entire two chars
     if (check(s.charAt(1)) == 0) {
        count[1] = check(s.charAt(0), s.charAt(1));
     } else {
        count[1] = check(s.charAt(0)) + check(s.charAt(0), s.charAt(1));    
     }

     // count[i] = count[i - 1] if s.charAt(i) is valid
     // or count[i] = count[i - 1] + count[i - 2] when s.charAt(i - 1) and s.charAt(i - 2) is valid.
     for (int i = 2; i < s.length(); i++) {
        if (check(s.charAt(i)) == 1) {
            count[i] = count[i - 1];
        }
        if (check(s.charAt(i - 1), s.charAt(i)) == 1) {
            count[i] += count[i - 2];
        }
     }

     return count[s.length() - 1];
}

// check if valid for single character
private int check(char c) {
    return (c == '0') ? 0 : 1;
}

// check if valid for twon combined character.
private int check(char c1, char c2) {
    return (c1 == '1' || (c1 == '2' && c2 <= '6')) ? 1 : 0;
}