๐ 91. ่งฃ็ ๆนๆณ
2022ๅนด10ๆ10ๆฅ
- algorithm
๐ 91. ่งฃ็ ๆนๆณ
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int numDecodings(String s) {
// ๆ่ทฏ๏ผ
// dp
int len = s.length();
int[] dp = new int[len + 1];
dp[0] = 1;
for(int i = 1; i <= len; i ++) {
int m = i - 1;
if(isValid(s, m, m)) {
dp[i] += dp[i - 1]; // ๅ็ฌๆ่ฏ
}
if(isValid(s, m - 1, m)) {
dp[i] += dp[i - 2]; // ๅๅ้ข็ๅ่ฏๆ่ฏ
}
}
return dp[len];
}
private boolean isValid(String s, int left, int right) {
int len = s.length();
if(left < 0 || right >= len) {
return false;
}
char high = s.charAt(left);
char low = s.charAt(right);
if(high == '1' && (low >= '0' && low <= '9')) {
return true;
}
if(high == '2' && (low >= '0' && low <= '6')) {
return true;
}
if(left == right && high >= '1' && high <= '9') {
return true;
}
return false;
}
}