Skip to content

Instantly share code, notes, and snippets.

@dryear
Created October 20, 2016 07:20
Show Gist options
  • Select an option

  • Save dryear/5b3fac367599ae695180b9738a75356f to your computer and use it in GitHub Desktop.

Select an option

Save dryear/5b3fac367599ae695180b9738a75356f to your computer and use it in GitHub Desktop.
LeetCode 91. Decode Ways
/**
* 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];
}
}
@QureshiAbraham
Copy link

It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=Z2NTdsOjvAQ&ab_channel=EricProgramming

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment