首页 > 代码库 > Decode Ways
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.
这道题有点像https://oj.leetcode.com/problems/climbing-stairs/爬梯子那道题,我在那道题的基础上用DP的思路,修修改改。写的略挫,一会儿去看看别人怎么A的
1 public class Solution { 2 public int numDecodings(String s) { 3 if(0 == s.length() || s.charAt(0) == ‘0‘) 4 return 0; 5 int ways[] = new int[s.length() + 1]; 6 for(int i = 0; i <= s.length(); i++){ 7 if(i == 1 || i == 0){ 8 ways[i] = 1; 9 }10 else{11 if(i < s.length() && s.charAt(i) == ‘0‘)12 {13 ways[i] = ways[i - 1];14 continue;15 }16 String subStr = s.substring(i - 2, i);17 int num = Integer.valueOf(subStr);18 if(num == 0)19 return 0;20 if(num > 26 && num % 10 == 0)21 return 0;22 else if(num <= 26 && s.charAt(i - 1) != ‘0‘ && s.charAt(i - 2) != ‘0‘)23 ways[i] = ways[i - 1] + ways[i - 2];24 else25 ways[i] = ways[i - 1]; 26 }//else27 }//for28 29 return ways[s.length()];30 }31 }
Decode Ways
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。