forked from algorithm008-class01/algorithm008-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDecodeWays.java
More file actions
120 lines (105 loc) · 3.09 KB
/
Copy pathPDecodeWays.java
File metadata and controls
120 lines (105 loc) · 3.09 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//一条包含字母 A-Z 的消息通过以下方式进行了编码:
//
// 'A' -> 1
//'B' -> 2
//...
//'Z' -> 26
//
//
// 给定一个只包含数字的非空字符串,请计算解码方法的总数。
//
// 示例 1:
//
// 输入: "12"
//输出: 2
//解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
//
//
// 示例 2:
//
// 输入: "226"
//输出: 3
//解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
//
// Related Topics 字符串 动态规划
package leetcode.editor.cn;
//Java:解码方法
public class PDecodeWays {
public static void main(String[] args) {
Solution solution = new PDecodeWays().new Solution();
solution.numDecodings("00");
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numDecodings(String s) {
// return digui(s,0);
return dp2(s);
}
private int digui(String s, int start) {
if (s.length() == start) {
return 1;
}
if (s.charAt(start) == '0') return 0;
int ans = digui(s, start + 1);
int help = 0;
if (start < s.length() - 1) {
if ((s.charAt(start) - '0') * 10 + (s.charAt(start + 1) - '0') <= 26) {
help = digui(s, start + 2);
}
}
return ans + help;
}
private int dp1(String s) {
int[] dp = new int[s.length() + 1];
dp[s.length()] = 1;
if (s.charAt(s.length() - 1) == '0') {
dp[s.length() - 1] = 0;
} else {
dp[s.length() - 1] = 1;
}
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == '0') {
dp[i] = 0;
continue;
}
int a1 = (s.charAt(i) - '0') * 10;
int a2 = (s.charAt(i + 1) - '0');
if (a1 + a2 <= 26) {
dp[i] = dp[i + 1] + dp[i + 2];
} else {
dp[i] = dp[i + 1];
}
}
return dp[0];
}
//省空间
private int dp2(String s) {
int last = 1;
int before = 0;
if (s.charAt(s.length() - 1) == '0') {
before = 0;
} else {
before = 1;
}
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == '0') {
last = before;
before = 0;
continue;
}
int a1 = (s.charAt(i) - '0') * 10;
int a2 = (s.charAt(i + 1) - '0');
if ( a1+a2 <= 26 ) {
int tmp = before;
before = before + last;
last = tmp;
} else {
last = before;
}
}
return before;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}