动态规划,分多情况讨论
import java.util.*; public class Solution { public int solve (String nums) { // write code here if (nums == null || nums.length() == 0) { return 0; } if (nums.equals("0")) { return 0; } int[] dp = new int[nums.length()+1]; dp[0] = 1; dp[1] = 1; for (int i = 2; i <= nums.length(); i++) { String str = nums.substring(i-2, i); if (str.charAt(1) == '0' && (str.charAt(0) > '2' || str.charAt(0) < '1')) { return 0; }else if (str.charAt(1) == '0' && (str.charAt(0) == '2' || str.charAt(0) == '1')) { dp[i] = dp[i-2]; }else if (str.compareTo("01") >=0 && str.compareTo("09") <= 0){ dp[i] = dp[i-1]; }else if (str.compareTo("11") >= 0 && str.compareTo("26") <= 0) { dp[i] = dp[i - 1] + dp[i - 2]; }else { dp[i] = dp[i-1]; } } return dp[nums.length()]; } }