Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

91. Decode Ways #15

Open
w4irdo opened this issue Aug 26, 2019 · 0 comments
Open

91. Decode Ways #15

w4irdo opened this issue Aug 26, 2019 · 0 comments

Comments

@w4irdo
Copy link
Owner

w4irdo commented Aug 26, 2019

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];
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant