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],条件要严格判断

注意事项:编码要把边界条件考虑情况,尽可能的限制

  1. public int numDecodings(String s) {
  2. if(s==null || s.length() == 0) return 0;
  3. if(s.compareTo("0")==0) return 0;
  4. int s1 = s.length();
  5. int[] res = new int[s1+1];
  6. res[0] = 1;
  7. for(int i=1;i<=s1;i++) {
  8. if(i>=2) {
  9. String str = s.substring(i-2,i);
  10. if(Integer.parseInt(str)<=26 && Integer.parseInt(str)>= 10)
  11. res[i] = res[i-2];
  12. }
  13. if(s.charAt(i-1)>'0' && s.charAt(i-1)<='9' )res[i] += res[i-1];
  14. }
  15. return res[s1];
  16. }
posted @ 2014-08-01 00:14  purejade  阅读(74)  评论(0编辑  收藏  举报