CS-Notes/notes/46. 把数字翻译成字符串.md
2020-11-17 00:32:18 +08:00

32 lines
1015 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 46. 把数字翻译成字符串
[Leetcode](https://leetcode.com/problems/decode-ways/description/)
## 题目描述
给定一个数字按照如下规则翻译成字符串1 翻译成a2 翻译成b... 26 翻译成z一个数字有多种翻译可能例如 12258 一共有 5 分别是 abbehlbehavehabyhlyh实现一个函数用来计算一个数字有多少种不同的翻译方法
## 解题思路
```java
public int numDecodings(String s) {
if (s == null || s.length() == 0)
return 0;
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= n; i++) {
int one = Integer.valueOf(s.substring(i - 1, i));
if (one != 0)
dp[i] += dp[i - 1];
if (s.charAt(i - 2) == '0')
continue;
int two = Integer.valueOf(s.substring(i - 2, i));
if (two <= 26)
dp[i] += dp[i - 2];
}
return dp[n];
}
```