public int numDecodings(String s) {
int len = 0;
if (s == null || (len = s.length()) == 0) {
return len;
}
char[] content = s.toCharArray();
int[] dp = new int[len];
// start with '0' is impossible and return 0;
if (content[0] == '0') {
return 0;
}
// dp[i] means the max decoration ways up to i-th index.
dp[0] = 1;
for (int i = 1; i <= len - 1; i++) {
char chNow = content[i];
char chBefore = content[i - 1];
// current char is 0, so it can't stand alone.
if (chNow == '0') {
// can't combine with former, return 0
if (chBefore != '1' && chBefore != '2') {
return 0;
} else {
// combine with former,so dp[i]= dp[i-2] (except for i==1)
dp[i] = (i == 1 ? 1 : dp[i - 2]);
}
} else {
// can stand alone or combine with former
if (chBefore == '1' || (chBefore == '2' && chNow <= '6')) {
dp[i] = dp[i - 1] + (i == 1 ? 1 : dp[i - 2]);
} else {
// only can stand alone.
dp[i] = dp[i - 1];
}
}
}
return dp[len - 1];
}
I
immortalCockroach
@immortalCockroach
2
Reputation
8
Posts
184
Profile views
0
Followers
0
Following
Posts made by immortalCockroach
-
Java dp solution beats 94.78% with explanations