Skip to content

91. Decode Ways #15

Open
Open
@w4irdo

Description

@w4irdo
class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = s.charAt(0) == '0' ? 0 : 1;
        
        for (int i = 2; i <= n; ++i) {
            int first = Integer.valueOf(s.substring(i - 1, i));
            if (first != 0) {
                dp[i] += dp[i - 1];
            }
            if (s.charAt(i - 2) == '0') {
                continue;
            }
            
            int second = Integer.valueOf(s.substring(i - 2, i));
            if (second >= 10 && second <= 26) {
                dp[i] += dp[i - 2];
            }
        }
        
        return dp[n];
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions