将前缀表达式转换为后缀表达式
我正在尝试实现一个程序,使用递归将前缀表达式更改为后缀表达式。
我已经写了我认为可行的内容,但我得到的是 aa/aa/*aa/aa/*-
而不是输出 ab/c*de+f*-
反而。
当我尝试获取 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;
}
}
}
I'm trying to implement a program that changes a prefix expression to a postfix one using recursion.
I've written what I thought would work but instead of the output ab/c*de+f*-
I get aa/aa/*aa/aa/*-
instead.
I think my code is getting stuck when I try to get the first character of String pre
or when I try to delete the first character of String pre
. Any suggestions/comments?
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,代码中的错误与计算
postfix1
和postfix2
的位置有关 - 请注意,您没有抵消postfix2
。要执行此递归,您需要了解几种情况:
这意味着当您遇到类似
+-abc
的内容时,您将执行以下步骤:这应该有效:
So the error in your code has to do with where you calculate
postfix1
andpostfix2
-- note that you're not offsettingpostfix2
.To do this recursion you need to understand a few cases:
This means when you encounter something like
+-abc
you will do the following steps:This should work: