JAVA concise solution, constant space


  • 0
    W
    public class Solution {
        public int numDecodings(String s) {
            if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;
            int lastTwo = 0, lastOne = 1;
            for (int i = 1; i < s.length(); i++) {
                int temp = lastOne;
                lastOne += lastTwo;
                lastTwo = temp;
                if (s.charAt(i) == '0') lastOne = 0;
                if (s.charAt(i - 1) == '0' || s.substring(i - 1, i + 1).compareTo("26") > 0) lastTwo = 0;
            }
            return lastOne + lastTwo;
        }
    }

Log in to reply
 

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