题解 | 把数字翻译成字符串
把数字翻译成字符串
https://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 解码 * @param nums string字符串 数字串 * @return int整型 */ public int solve (String nums) { char[] charArray = nums.toCharArray(); int[] total = new int[nums.length() + 1]; total[0] = 1; for (int i = 1; i <= charArray.length; i++) { if (i == 1) { if (charArray[i - 1] <= '0' || charArray[i - 1] > '9') { return 0; } total[i] = 1; continue; } if (charArray[i - 1] == '0' && !(charArray[i - 2] >= '1' && charArray[i - 2] <= '2')) { return 0; } if (charArray[i - 1] < '0' || charArray[i - 1] > '9') { return 0; } Boolean choose = (charArray[i - 2] == '1' && charArray[i - 1] <= '9' && charArray[i - 1] >= '0' ) || (charArray[i - 2] == '2' && charArray[i - 1] <= '6' && charArray[i - 1] >= '0' ) ; if (i == 2) { if (charArray[i-1] == '0' || !choose) { total[i] = 1; }else { total[i] = 2; } continue; } if (charArray[i-1] == '0' || !choose) { total[i] = total[i - 1]; }else { total[i] = total[i - 2] + total[i - 1]; } } return total[charArray.length]; // for (int i = 1; i < nums.length(); i++) { // if (nums.charAt(i) == '0') // if (nums.charAt(i - 1) != '1' && nums.charAt(i - 1) != '2') // return 0; // } // String[] split = nums.split(""); // return solveStr(split, split.length - 1); } public int solveStr ( String[] split, int n) { String s = split[n]; if (n == 0 && s.equals("0")) { return 0; } if (n == 0) { return 1; } if (split[n - 1].equals("0")) { return solveStr(split, n - 1); } String s1 = split[n - 1] + s; int i = Integer.parseInt(s1); if (n == 1) { if (s.equals("0")) { if (i < 27) { return solveStr(split, n - 1); } } if (i < 27) { return 1 + solveStr(split, n - 1); } return solveStr(split, n - 1); } if (split[n - 1].equals("0")) { return solveStr(split, n - 1); } if (s.equals("0")) { // if (i < 27) { // return solveStr(split, n - 2) + solveStr(split, n - 1); // } return solveStr(split, n - 1); } else { if (i < 27) { return solveStr(split, n - 2) + solveStr(split, n - 1); } return solveStr(split, n - 1) ; } } }