Decode Ways
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.
思想:考虑清楚,不要省事。。如果一个数字则该数字(0,9];如果两个数字,则[10,26],条件要严格判断
注意事项:编码要把边界条件考虑情况,尽可能的限制
- public int numDecodings(String s) {
- if(s==null || s.length() == 0) return 0;
- if(s.compareTo("0")==0) return 0;
- int s1 = s.length();
- int[] res = new int[s1+1];
- res[0] = 1;
- for(int i=1;i<=s1;i++) {
- if(i>=2) {
- String str = s.substring(i-2,i);
- if(Integer.parseInt(str)<=26 && Integer.parseInt(str)>= 10)
- res[i] = res[i-2];
- }
- if(s.charAt(i-1)>'0' && s.charAt(i-1)<='9' )res[i] += res[i-1];
- }
- return res[s1];
- }