translate numbers to strings
Topic description
Given a number, translate it into a string according to the following rules: 1 translates to "a", 2 translates to "b"... 26 translates to "z". There are many possible translations for a number. For example, 12258 has 5 kinds, which are abbeh, lbeh, aveh, abyh, and lyh. Implement a function that counts how many different translation methods a number has.
title link : [translate numbers into strings]()
code
/**
* 标题:把数字翻译成字符串
* 题目描述
* 给定一个数字,按照如下规则翻译成字符串:1 翻译成“a”,2 翻译成“b”... 26 翻译成“z”。一个数字有多种翻译可能,例如 12258 一共有 5 种,
* 分别是 abbeh,lbeh,aveh,abyh,lyh。实现一个函数,用来计算一个数字有多少种不同的翻译方法。
*/
public class Jz71 {
/**
* 动态规划
*
* @param s
* @return
*/
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];
}
public static void main(String[] args) {
Jz71 jz71 = new Jz71();
System.out.println(jz71.numDecodings("12258"));
}
}
[Daily Message] If the child does not learn, it is not appropriate; if the young does not learn, what is the old man.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。