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

Create 91-Decode-Ways.java#591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Ahmad-A0 merged 1 commit intoneetcode-gh:mainfromcoded9:patch-3
Jul 23, 2022
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletionsjava/91-Decode-Ways.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
// Optimal
class Solution {

public int numDecodings(String s){
int[] dp = new int[s.length()+1];
int twoBack = 1; // empty string
int oneBack = s.charAt(0) == '0' ? 0: 1;
int current = oneBack;
for(int i = 2; i < s.length()+1; i++){
current = 0;
if(s.charAt(i-1) != '0'){
current += oneBack;
}
if(s.charAt(i-2) == '1' || (s.charAt(i-2) == '2' && s.charAt(i-1) < '7')){
current += twoBack;
}
twoBack = oneBack;
oneBack = current;
}
return current;
}

}

//bottom up
class Solution {

public int numDecodings(String s){
int[] dp = new int[s.length()+1];
dp[0] = 1; // empty string
dp[1] = s.charAt(0) == '0' ? 0: 1;
for(int i = 2; i < s.length()+1; i++){
if(s.charAt(i-1) != '0'){
dp[i] += dp[i-1];
}
if(s.charAt(i-2) == '1' || (s.charAt(i-2) == '2' && s.charAt(i-1) < '7')){
dp[i] += dp[i-2];
}
}
return dp[s.length()];
}
}

//top down with memoization
class Solution {

public int numDecodings(String s){
return numDecodings(s,0,new Integer[s.length()]);
}

private int numDecodings(String s, int i,Integer[] dp){
if(i == s.length()) return 1;
if(s.charAt(i) == '0') return 0;
if(dp[i] != null) return dp[i];
int count = 0;
count += numDecodings(s,i+1,dp);
if(i < s.length()-1 && (s.charAt(i) == '1' || s.charAt(i) == '2' && s.charAt(i+1) < '7')){
count += numDecodings(s,i+2,dp);
}
dp[i] = count;
return dp[i];
}
}



[8]ページ先頭

©2009-2025 Movatter.jp