forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode-ways.java
More file actions
43 lines (32 loc) · 929 Bytes
/
Copy pathdecode-ways.java
File metadata and controls
43 lines (32 loc) · 929 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int numDecodings(String s) {
int dp[]=new int[s.length()+1];
Arrays.fill(dp,-1);
return solve(s,0,dp);
}
static int solve(String s,int i,int dp[]){
if(i>=s.length()) return 1;
int l=0;
int r=0;
if(dp[i]!=-1) return dp[i];
if(i+1<=s.length()){
String t=s.substring(i,i+1);
if(check(t)){
l=solve(s,i+1,dp);
}
}
if(i+2<=s.length()){
String t=s.substring(i,i+2);
if(check(t))
r=solve(s,i+2,dp);
}
return dp[i]=l+r;
}
static boolean check(String s){
if(s.charAt(0)=='0') return false;
if(s.length()==1) return true;
int t=Integer.parseInt(s);
if(t>=10 && t<=26) return true;
return false;
}
}