Share my readable code


  • 0
    S
    public class Solution {
    public int numDecodings(String s) {
        // case1: 101
        // case2: 509
        if (s == null || s.length() == 0 || s.charAt(0) == '0')
            return 0;
            
        int prepre = 1;
        int pre = 1;
        int res = 1;
        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) == '0') {
                if (s.charAt(i - 1) == '1' || s.charAt(i - 1) == '2') {
                    res = prepre;
                } else {
                    res = 0;
                }
            } else if (s.charAt(i) >= '1' && s.charAt(i) <= '6') {
                if (s.charAt(i - 1) == '1' || s.charAt(i - 1) == '2') {
                    res = pre + prepre;
                } else {
                    res  = pre;
                }
            } else if (s.charAt(i) >= '7' && s.charAt(i) <= '9') {
                if (s.charAt(i - 1) == '1') {
                    res = pre + prepre;
                } else {
                    res  = pre;
                }
            }
            prepre = pre;
            pre = res;
        }
        return res;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.