Statistical letter decoding method Total <Data Structures and Algorithms> recursive algorithm

  Entitled LeetCode first 91 questions, a message containing the letters AZ is encoded by:

  'A' -> 1

  'B' -> 2

  …

  'Z' -> 26

  Given contain only a non-empty string of numbers, the total number of decoding approach.

 

  The title can be used to resolve recursive, directly attached to the code:

 

public static int numDecodings(String s) {
if (s.charAt(0) == '0') return 0; char[] chars = s.toCharArray(); return decode(chars, chars.length - 1); }
// string into a character array, using a recursive function decode, forward recursively from the last character
Private int
decode ( char [] chars, int index) { // if the index is 0, the processing head to a string , IF (index <= 0) {
      return 1;
   }
   int count = 0; char curr = chars[index]; char prev = chars[index - 1]; // current character than "0" is large, the direct use of the resulting string before it obtained IF (Curr> '0' ) { count = decode(chars, index - 1); } // two numbers of characters needs to judge whether a number between 1-26 IF (PREV == '. 1' || (PREV == '2' && Curr <= '. 6' )) { count += decode(chars, index - 2); } return count; }

 

 

 

Guess you like

Origin www.cnblogs.com/wangxiaoqian/p/11917403.html