Concise Java solution.


  • 0
    V

    Please let me know if the code can be improved.

    public class Solution {
        
        boolean isValid(String s, int i) {
            int val = s.charAt(i) - '0';
            val = val * 10 + (s.charAt(i + 1) - '0');
            
            return val <= 26; 
        }
        
        public int numDecodings(String s) {
            if (s == null || s.length() == 0) return 0;
            int n = s.length();
            int second = 1;
            int first = (s.charAt(n - 1) == '0') ? 0 : 1;
            
            for (int i =  n - 2; i >= 0; i--) {
                if (s.charAt(i) == '0') {
                    second = first;
                    first = 0;
                } else {
                    int temp = first;
                    if (isValid(s, i)) {
                        temp += second;
                    }
                    second = first;
                    first = temp;
                }
            }
            
            return first;
        }
    }
    

Log in to reply
 

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