Java 将前缀表达式转换为后缀

Java 将前缀表达式转换为后缀,java,recursion,prefix,postfix-notation,Java,Recursion,Prefix,Postfix Notation,我正在尝试实现一个程序,使用递归将前缀表达式更改为后缀表达式 我已经写了我认为有效的东西,但是我得到的不是输出ab/c*de+f*-而是aa/aa/*aa/aa/*- 当我尝试获取String pre的第一个字符或尝试删除String pre的第一个字符时,我认为我的代码被卡住了。有什么建议/意见吗 public class Prefix2Postfix { public static final String prefixInput ="-*/abc*+def";

我正在尝试实现一个程序,使用递归将前缀表达式更改为后缀表达式

我已经写了我认为有效的东西,但是我得到的不是输出
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;
            }
        }
    }

因此,代码中的错误与计算
postfix1
postfix2
的位置有关——请注意,您没有偏移
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+" f(“+-abc”)=>返回f(“-abc”)+“+”+f(rem1) f(“-abc”)=>返回f(“abc”)+“-”+f(rem2) f(“abc”)=>返回“ab” rem2=“c”(字符串的剩余部分) f(“c”)=>返回“c” rem1=“”(字符串中没有要分析的内容) 哪一个构成了“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);
    }

}
publicstaticstringpre2post(stringpre){

如果(pre.length()啊,我的眼睛!你能修好缩进吗?对不起!我总是很难让我的代码显示为代码。我总是要弄乱缩进才能这样做。试着选择代码行并点击ctrl-k(或101按钮)。这真的很有帮助。谢谢你的解释!