Created
October 20, 2016 07:20
-
-
Save dryear/5b3fac367599ae695180b9738a75356f to your computer and use it in GitHub Desktop.
LeetCode 91. Decode Ways
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * https://leetcode.com/problems/decode-ways/ | |
| * | |
| * O(n) runtime, O(1) space | |
| * | |
| * this is a typical DP question | |
| * use a rolling array to get O(1) space | |
| */ | |
| public class Solution { | |
| public int numDecodings(String s) { | |
| if (s == null || s.length() == 0) { | |
| return 0; | |
| } | |
| if (s.length() == 1) { | |
| return s.charAt(0) != '0' ? 1 : 0; | |
| } | |
| int[] nums = new int[3]; | |
| if (s.charAt(0) != '0') { | |
| nums[0] = 1; | |
| } else { | |
| return 0; | |
| } | |
| int n = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); | |
| nums[1] = (s.charAt(1) != '0' ? nums[0] : 0) + | |
| (10 <= n && n <= 26 ? 1 : 0); | |
| for (int i = 2; i < s.length(); i++) { | |
| n = (s.charAt(i-1) - '0') * 10 + (s.charAt(i) - '0'); | |
| nums[i%3] = (s.charAt(i) != '0' ? nums[(i-1)%3] : 0) + | |
| (10 <= n && n <= 26 ? nums[(i-2)%3] : 0); | |
| } | |
| return nums[(s.length()-1)%3]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=Z2NTdsOjvAQ&ab_channel=EricProgramming