Review an answer - Decode Ways

前端 未结 7 1257
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 19:36

I\'m trying to solve a question and my question here is why doesn\'t my solution work?. Here\'s the question and below\'s the answer.

Question taken fr

7条回答
  •  梦谈多话
    2021-01-31 20:35

    Java solution with space and time complexity O(n)

    public int numDecodings(String s) {
        int n = s.length();
        if (n > 0 && s.charAt(0) == '0')
            return 0;
        int[] d = new int[n + 1];
        d[0] = 1;
        d[1] = s.charAt(0) != '0' ? 1 : 0;
        for (int i = 2; i <= n; i++) {
            if (s.charAt(i - 1) > '0')
                d[i] = d[i] + d[i - 1];
    
            if (s.charAt(i - 2) == '2' && s.charAt(i - 1) < '7')
                d[i] = d[i - 2] + d[i];
            if (s.charAt(i - 2) == '1' && s.charAt(i - 1) <= '9')
                d[i] = d[i - 2] + d[i];
        }
        return d[n];
    }
    

提交回复
热议问题