Clean Java DP Solution


  • 0

    ...
    public class Solution {

    public int numDecodings(String s) {
    
    	if (s == null || s.length() == 0) {
    		return 0;
    	}
    
    	int[] numWays = new int[s.length() + 1];
    	numWays[0] = 1;
    
    	if (Character.getNumericValue(s.charAt(0)) != 0) {
    		numWays[1] = 1;
    	} else {
    		numWays[1] = 0;
    	}
    
    	for (int i = 1; i < s.length(); i++) {
    
    		if (Character.getNumericValue(s.charAt(i)) != 0) {
    			numWays[i + 1] = numWays[i + 1] + numWays[i];
    		}
    
    		if (Character.getNumericValue(s.charAt(i - 1)) != 0) {
    			int temp = Integer.valueOf(s.substring(i - 1, i + 1));
    
    			if (temp >= 1 && temp <= 26) {
    				numWays[i + 1] = numWays[i + 1] + numWays[i - 1];
    			}
    		}
    	}
    
    	return numWays[s.length()];
    }
    

    ...

    }


Log in to reply
 

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