A message containing letters from A-Z
is being encoded to numbers using the following mapping:
‘A‘ -> 1 ‘B‘ -> 2 ... ‘Z‘ -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12).
class Solution { public int numDecodings(String s) { int[] arr = new int[s.length() + 1]; arr[0] = 1; // for case of ‘0‘; arr[1] = s.charAt(0) == ‘0‘ ? 0 : 1; for (int i = 2; i <= s.length(); i++) { int preOne = Integer.valueOf(s.substring(i - 1, i)); int preTwo = Integer.valueOf(s.substring(i - 2, i)); if (preOne >= 1 && preOne <= 9) { arr[i] += arr[i - 1]; } if (preTwo >= 10 && preTwo <= 26) { arr[i] += arr[i - 2]; } } return arr[s.length()]; } }
原文地址:https://www.cnblogs.com/xuanlu/p/12047192.html
时间: 2024-11-09 07:58:21