File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments