lintcode(512)解码方法

xiaoxiao2021-02-27  155

描述:

有一个消息包含A-Z通过以下规则编码

'A' -> 1 'B' -> 2 ... 'Z' -> 26

现在给你一个加密过后的消息,问有几种解码的方式

样例:

给你的消息为12,有两种方式解码 AB(12) 或者 L(12). 所以返回 2

思路:

动态规划,相邻两位一起看00 不符合条件, 01 - 09 只有一种 ,10,20只有一种,超过27不符合条件,其余可以有两种方案

public class Solution { /** * @param s a string, encoded message * @return an integer, the number of ways decoding */ public int numDecodings(String s) { // Write your code here if(s == null || s.length() == 0 || s.charAt(0) == '0'){ return 0; } int count1 = 1 , count2 = 1 , count3 = 1; for(int i = 1;i<s.length();i++){ if(s.charAt(i) == '0'){ int a = s.charAt(i - 1) - '0'; if(a == 1 || a == 2){ count3 = count1; }else{ return 0; } }else{ int a = s.charAt(i - 1) - '0'; int b = s.charAt(i) - '0'; int c = 10*a + b; if(c >= 27 || c < 10){ count3 = count2; }else{ count3 = count1 + count2; } } count1 = count2; count2 = count3; } return count3; } }

转载请注明原文地址: https://www.6miu.com/read-15068.html

最新回复(0)