File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Date: Dec 25, 2014
4
+ Problem: Decode Ways
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/decode-ways/
7
+ Notes:
8
+ A message containing letters from A-Z is being encoded to numbers using the following mapping:
9
+ 'A' -> 1
10
+ 'B' -> 2
11
+ ...
12
+ 'Z' -> 26
13
+ Given an encoded message containing digits, determine the total number of ways to decode it.
14
+ For example,
15
+ Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
16
+ The number of ways decoding "12" is 2.
17
+
18
+ Solution: 1. dp. Time : O(n); Space : O(1).
19
+ */
20
+
21
+ public class Solution {
22
+ public int numDecodings (String s ) {
23
+ if (s .length () == 0 || s .charAt (0 ) == '0' ) return 0 ;
24
+ int N = s .length ();
25
+ int f0 = 1 , f1 = 1 ;
26
+ for (int i = 1 ; i < N ; ++i ) {
27
+ if (s .charAt (i ) == '0' ) f1 = 0 ;
28
+ int num = s .charAt (i ) - '0' + (s .charAt (i -1 ) - '0' ) * 10 ;
29
+ if (num < 10 || num > 26 ) {
30
+ f0 = 0 ;
31
+ }
32
+ int tmp = f1 ;
33
+ f1 = f1 + f0 ;
34
+ f0 = tmp ;
35
+ }
36
+ return f1 ;
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments