My Java solution with O(1) space


  • 0
    B
    public int numDecodings(String s) {
            if (s.length() == 0) return 0;
            
            int sum = 1, preSum = 0;
            char pre = '0';
            
            for (char current: s.toCharArray()) {
                int copyOfSum = sum, currentSum = 0;
                
                if (current == '0' && pre == '0') sum = 0;
                if (current > '0') currentSum = sum;
                if (pre == '1' || (pre == '2' && current <= '6')) currentSum += preSum;
                
                sum = currentSum;
                preSum = copyOfSum;
                pre = current;
            }
            
            return sum;
        }
    

Log in to reply
 

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