Decode Ways
来源:互联网 发布:图片日语翻译软件 编辑:程序博客网 时间:2024/06/10 03:48
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.
public class Solution { public int numDecodings(String s) { if (s == null || s.length() == 0) return 0; if (s.length() == 1) {if (s.equals("0")) {return 0;} else {return 1;}} if (s.length() == 2) { if (s.charAt(0) == '0') return 0; int value = Integer.parseInt(s); if (value == 10 || value == 20) return 1; if (value <= 26) return 2; if (value % 10 == 0) return 0; return 1; } int preV = numDecodings(s.substring(0, 2)) > 0 ? 1 : 0; return numDecodings(s.substring(0, 1)) * numDecodings(s.substring(1, s.length())) + preV * numDecodings(s.substring(2, s.length())); }}
Another version:
public class Solution { public int numDecodings(String s) { if (s.length() == 0) return 0; int len = s.length(); if (len < 1) return 0; int[] numarray = new int[len]; int i = len - 1; numarray[i] = (s.charAt(i) == '0') ? 0 : 1; i--; while (i >= 0) { if (s.charAt(i) == '0') numarray[i] = 0; else if (s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i+1) <= '6')) if (i == len - 2) { numarray[i] = numarray[i+1] + 1; } else { numarray[i] = numarray[i+1] + numarray[i+2]; } else numarray[i] = numarray[i+1]; i--; } return numarray[0]; }}
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- pthread最简单的多线程编程-002
- 解决eclipse和myeclipse下不能自动提示代码的问题
- Linux内核中的定时
- CSS3下的147个颜色名称实例页面
- 读书笔记: processor architecture<computer system a programmer perspective第二章>
- Decode Ways
- 读书笔记《30天自制操作系统》day10
- Makefile初步(打桩先,晚上完善)
- PBOC/EMV-交易流程详解--POS与卡片的数据交互进行分析
- Linux 定时器setitimer()
- Spring_009_DataSource
- 大家小心了《C程序设计伴侣》出现了!!!
- Spring security2 登录例子1
- 元器件选型参考:华强北现货搜索器