2015-02-12 33 views
3

問題陳述: 給定一個數字序列,計算給定數字序列的可能解碼。將基本的遞歸算法轉換爲動態的自下而上列表算法

實例:

12給出2:

'AB' 和 'L'

123給出3:

'ABC','LC'和'AW'

這裏是我的嘗試:

import java.util.*; 

public class decodingcount { 

static int calls = 0;  
static Map<Integer, String> codes = new HashMap<Integer, String>(); 

private static void construct(){ 
codes.put(1, "A"); 
codes.put(2, "B"); 
codes.put(3, "C"); 
codes.put(4, "D"); 
//..so on 
} 

private static int decode(String str, String built){ 

    construct();   

    int n = str.length(); 
    int count = 0; 

    if (n == 0) { 
     System.out.println(built); 
     return 1; 
    } 

     // If you have 0's, then they don't have a corresponding singular letter. Break off the recursion. 
     if (str.substring(0, 1).equals("0")) 
      return 0; 

     String x = codes.get(Integer.parseInt(str.substring(0, 1))); 

     if (x == null) 
      return 0; 

     count = decode(str.substring(1), built+x); 

     if (n > 1) { 

      // If it's more than 26, it doesn't have a corresponding letter. Break off the recursion. 
      if (Integer.parseInt(str.substring(0, 2)) > 26) 
       return 0; 

      String y = codes.get(Integer.parseInt(str.substring(0, 2))); 

      count += decode(str.substring(2), built+y); 
     } 

     return count; 
    } 

    public static void main(String[] args) { 
    System.out.println(decode(args[0], "")); 
     } 
    } 

這個運行在指數時間。我真的很努力將其轉換爲動態編程自下而上的製表算法。 Here is my attempt 。它返回0.將感謝任何幫助。

+0

什麼輸入,它給0? – sashas 2015-02-12 01:24:42

+0

如果輸入字符串包含零,那麼答案應該是零,你可能會給出一個輸入,如「1203」,代碼對我來說很好 – sashas 2015-02-12 01:27:12

+0

你有一個重大的錯誤。儘管有一個0,'1203'有一個解碼,'ATC'。同樣'456'解碼,'DEF',儘管有2個數字序列超過26. – btilly 2015-02-12 02:23:18

回答

3

工作代碼:

private static int decode(String str) { 

    construct(); 

    int n = str.length(); 
    int[] count = new int[n]; 

    count[0] = 1; 

    for (int i = 1; i < n; i++) { 
     String x = codes.get(Integer.parseInt(str.substring(i, i + 1))); 
     if (str.charAt(i) != '0') 
      count[i] = count[i - 1]; 
     if (Integer.parseInt(str.substring(i - 1, i + 1)) <= 26 && str.charAt(i - 1) != '0') 
      count[i] += (i - 2 >= 0 ? count[i - 2] : 1); 
    } 

    return count[n - 1]; 

} 
+0

如果第一個數字是零怎麼辦? – Lurr 2015-02-12 08:20:24

+0

@Lurr,這不是一個有效的輸入,OP已經在他的評論中提到了完整的問題 – 2015-02-12 08:26:50

+0

@PhamTrung非常感謝。我想我現在正在製表。這很棒。 – Siddhartha 2015-02-12 19:59:00