Skip to content

Commit 55f640c

Browse files
committed
feat: decode ways
1 parent f05da5c commit 55f640c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

decode-ways/minjigo.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
*/
8+
class Solution {
9+
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];
14+
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];
18+
}
19+
return dp[s.length()-1];
20+
}
21+
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;
27+
}
28+
}

0 commit comments

Comments
 (0)