Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitccc8d0d

Browse files
refactor 91
1 parentb52ac60 commitccc8d0d

File tree

1 file changed

+22
-37
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-37
lines changed
Lines changed: 22 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,34 @@
11
packagecom.fishercoder.solutions;
22

3-
/**
4-
* 91. Decode Ways
5-
*
6-
* A message containing letters from A-Z is being encoded to numbers using the following mapping:
7-
8-
'A' -> 1
9-
'B' -> 2
10-
...
11-
'Z' -> 26
12-
Given an encoded message containing digits, determine the total number of ways to decode it.
13-
14-
For example,
15-
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
16-
17-
The number of ways decoding "12" is 2.
18-
*/
193
publicclass_91 {
20-
/**Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation
4+
/**
5+
* Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation
216
* I used a dp array of size n + 1 to save subproblem solutions.
227
* dp[0] means an empty string will have one way to decode,
238
* dp[1] means the way to decode a string of size 1.
24-
*
259
* I then check one digit and two digit combination and save the results along the way.
26-
* In the end, dp[n] will be the end result.*/
10+
* In the end, dp[n] will be the end result.
11+
*/
2712

2813
publicstaticclassSolution1 {
29-
publicintnumDecodings(Strings) {
30-
if (s ==null ||s.length() ==0) {
31-
return0;
32-
}
33-
int[]dp =newint[s.length() +1];
34-
dp[0] =1;
35-
dp[1] = (s.charAt(0) !='0') ?1 :0;
36-
for (inti =2;i <=s.length();i++) {
37-
intfirst =Integer.valueOf(s.substring(i -1,i));
38-
intsecond =Integer.valueOf(s.substring(i -2,i));
39-
if (first >0 &&first <=9) {
40-
dp[i] +=dp[i -1];
41-
}
42-
if (second >=10 &&second <=26) {
43-
dp[i] +=dp[i -2];
44-
}
14+
publicintnumDecodings(Strings) {
15+
if (s ==null ||s.length() ==0) {
16+
return0;
17+
}
18+
int[]dp =newint[s.length() +1];
19+
dp[0] =1;
20+
dp[1] = (s.charAt(0) !='0') ?1 :0;
21+
for (inti =2;i <=s.length();i++) {
22+
intfirst =Integer.valueOf(s.substring(i -1,i));
23+
intsecond =Integer.valueOf(s.substring(i -2,i));
24+
if (first >0 &&first <=9) {
25+
dp[i] +=dp[i -1];
26+
}
27+
if (second >=10 &&second <=26) {
28+
dp[i] +=dp[i -2];
29+
}
30+
}
31+
returndp[s.length()];
4532
}
46-
returndp[s.length()];
47-
}
4833
}
4934
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp