Decode Ways


public class Solution {
public int numDecodings(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if (s.length() == 0)
return s.length();
else if (s.startsWith("0"))
return 0;
else if (s.length() == 1){
return 1;
}

else {
int sum = 0;
int temp = Integer.parseInt(s.substring(0,2));
if (temp <= 26 && temp > 0)
if (s.length() > 2)
sum += numDecodings(s.substring(2, s.length()));
else
sum += 1;
sum += numDecodings(s.substring(1, s.length()));
return sum;
}
}
}

递归的方法,就是需要注意0开头的字符串是不能被parse的。但是。。。。大数据超时了??唉。。。
看了代码,发现确实有这个问题,numDecodings(s.substring(1, s.length()))还会重复计算之前计算过的numDecodings(s.substring(2, s.length()))
那么只能逆着递推了(类似动规?)

public class Solution {
public int numDecodings(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int length = s.length();
if (length == 0)
return 0;
int[] count = new int[length+1];
count[length] = 1;
if (s.charAt(length-1) =='0')
count[length-1] = 0;
else
count[length-1] = 1;
for (int i = length-2; i >=0; --i){
if (s.charAt(i) != '0')
count[i] += count[i+1];
else
continue;
int temp = Integer.parseInt(s.substring(i,i+2));
if (temp <=26)
count[i] += count[i+2];
}
return count[0];
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值