Java solution, 2 ms, nothing special


  • 0
    A
    public int numDecodings(String s) {
        if (s.length() < 1) return 0;
        int[] ways = new int[s.length()];
        ways[s.length()-1] = s.charAt(s.length() - 1) == '0' ? 0 : 1;
        for (int i = s.length() - 2; i >= 0; i--) {
            if (s.charAt(i) == '0')
                if (s.charAt(i+1) == '0') return 0;
                else continue;
            ways[i] = ways[i+1];
            if ((s.charAt(i) == '1') || (s.charAt(i) == '2' && s.charAt(i+1) < '7'))
                ways[i] += i + 2 >= s.length() ? 1 : ways[i+2];
        }
        return ways[0];
    }

Log in to reply
 

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