2010-11-09 103 views
2

我試圖實現一個程序,使用遞歸將前綴表達式更改爲後綴表達式。將前綴表達式轉換爲後綴

我寫了我認爲會工作,而不是輸出ab/c*de+f*-而是我得到aa/aa/*aa/aa/*-

我想我的代碼在我試圖獲取String pre的第一個字符時或當我嘗試刪除String pre的第一個字符時卡住了。任何建議/意見?

public class Prefix2Postfix { 
     public static final String prefixInput ="-*/abc*+def"; 
     //desired postfix output is "ab/c*de+f*-" 

     public static void main (String[] args){ 
      System.out.println(pre2Post(prefixInput)); 
     } 

     public static String pre2Post(String pre){ 
      //find length of string 
      int length = pre.length(); 

      //ch = first character of pre 
      char ch = pre.charAt(0); 

      //delete first character of pre 
      pre = pre.substring(1,length); 
      if(Character.isLetter(ch)){ 
       //base case: single identifier expression 
       return (new Character(ch)).toString(ch); 
      }else{ 
       //ch is an operator 
       String postfix1 = pre2Post(pre); 
       String postfix2 = pre2Post(pre); 
       return postfix1 + postfix2 + ch; 
      } 
     } 
    } 
+1

啊,我的眼睛!你能修好縮進嗎? – 2010-11-09 00:39:42

+0

對不起!我總是遇到麻煩,試圖使我的代碼顯示爲代碼。我總是最終不得不搞亂縮進。 – Bell 2010-11-09 01:38:28

+0

嘗試選擇代碼行並按ctrl-k(或101按鈕)。 – 2010-11-09 01:41:43

回答

2

所以在你的代碼中的錯誤與在那裏你計算postfix1postfix2做 - 注意,你不抵消postfix2

要做到這一點遞歸您需要了解一些情況:

  • 當你遇到你需要遞歸和操作者移動到右側,然後處理具有字符串的任何剩餘部分的操作沒有經過處理
  • 當你遇到一個字母和運營商,你應該只返回信
  • 當你遇到了兩封信,你應該只返回這兩個字母

這意味着當你遇到像+-abc你會做以下步驟:

 
f("+-abc") => return f("-abc") + "+" + f(rem1) 
f("-abc") => return f("abc") + "-" + f(rem2) 
    f("abc") => return "ab" 
    rem2 = "c" (remainder of the string) 
    f("c") => return "c" 
rem1 = "" (nothing left in the string to parse) 

which constructs "ab-c+" 

這應該工作:

public static String pre2post(String pre){ 
    if(pre.length() <= 1){ 
     return pre; 
    } 

    if(!Character.isLetter(pre.charAt(0))){ 
     String a = pre2post(pre.substring(1)) + pre.charAt(0); 
     String b = pre2post(pre.substring(a.length())); 
     return a + b; 
    }else if(!Character.isLetter(pre.charAt(1))){ 
     return pre.substring(0,1); 
    }else{ 
     return pre.substring(0,2); 
    } 

} 
+0

這真的很有幫助。感謝您的解釋! – Bell 2010-11-09 05:51:20