Skip to content

Commit bff3394

Browse files
committed
feat: decode-ways
1 parent 5959fff commit bff3394

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

decode-ways/minji-go.java

+27-21
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,34 @@
1-
/*
2-
Problem: https://leetcode.com/problems/decode-ways/
3-
Description: Given a string s containing only digits, return the number of ways to decode it
4-
Concept: String, Dynamic Programming
5-
Time Complexity: O(N), Runtime 1ms
6-
Space Complexity: O(N), Memory 42.12MB
7-
*/
1+
/**
2+
* <a href="https://leetcode.com/problems/decode-ways/">week03-5.decode-ways</a>
3+
* <li>Description: return the number of ways to decode it </li>
4+
* <li>Topics: String, Dynamic Programming </li>
5+
* <li>Time Complexity: O(N), Runtime 1ms </li>
6+
* <li>Space Complexity: O(1), Memory 41.8MB</li>
7+
*/
88
class Solution {
99
public int numDecodings(String s) {
10-
int[] dp = new int[s.length()];
11-
if(decode(s.substring(0, 1))) dp[0]=1;
12-
if(s.length()>1 && decode(s.substring(1, 2))) dp[1]+=dp[0];
13-
if(s.length()>1 && decode(s.substring(0, 2))) dp[1]+=dp[0];
10+
if (s.charAt(0) == '0') {
11+
return 0;
12+
}
13+
14+
int last2 = 1;
15+
int last1 = 1;
16+
17+
for (int i = 1; i < s.length(); i++) {
18+
int curr = 0;
19+
if (s.charAt(i) != '0') {
20+
curr += last1;
21+
}
1422

15-
for(int i=2; i<s.length(); i++){
16-
if(decode(s.substring(i,i+1))) dp[i]+=dp[i-1];
17-
if(decode(s.substring(i-1,i+1))) dp[i]+=dp[i-2];
23+
int num = Integer.parseInt(s.substring(i - 1, i + 1));
24+
if (num >= 10 && num <= 26) {
25+
curr += last2;
26+
}
27+
28+
last2 = last1;
29+
last1 = curr;
1830
}
19-
return dp[s.length()-1];
20-
}
2131

22-
public boolean decode(String s){
23-
int num = Integer.parseInt(s);
24-
int numLength = (int) Math.log10(num) + 1;
25-
if(num<0 || num>26 || numLength != s.length()) return false;
26-
return true;
32+
return last1;
2733
}
2834
}

0 commit comments

Comments
 (0)