您的位置:首页 > 其它

LeetCode 91. Decode Ways

2017-04-13 16:54 375 查看
题目如下:

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.


思路:

思路很简单,就是要检查s.charAt(i)和s.char(i-1)是否能构成一个字母,如果不能res[i]=res[i-1],如果能res[i]=res[i-1]+res[i-2];

但难处在于处理s.charAt(i)=='0'的各种情况,还有边界条件要处理好。

本体代码:

/**
* Created by yuanxu on 17/4/13.
*/
public class DP91 {

public static int numDecodings(String s) {
int len = s.length();
if (len == 0) return 0;
if (s.charAt(0) == '0')  return 0;

// for both s.char(i) and res[i], make i begins with 1
s = '0' + s;
int res[] = new int[len+1];

res[0] = 1; // for convince
res[1] = 1;

for (int i=2; i<=len; i++) {
if (s.charAt(i) == '0') {
if (s.charAt(i-1) =='1' || s.charAt(i-1) =='2') {
res[i] = res[i-2];
} else {
return 0;
}
} else {
res[i] = res[i-1];
if (s.charAt(i-1) == '1'|| (s.charAt(i-1)=='2' && s.charAt(i) < '7')) {
res[i] += res[i-2];
}
}
}
return res[len];
}

/**
*
* @test
*/
public  static void main(String[] args) {
//        String s = "12312";
//        String s = "0";
//        String s = "01";
//        String s = "10";
String s = "110";
System.out.println(numDecodings(s));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: