在调车场中保留括号
我正在研究本质上是调车场算法,但将中缀移动到前缀而不是 RPN 我正在努力保留括号,但我却经历了一段痛苦的时光。目前我的代码是
String s = inFixList.get(i);
Stack<Character> opStack = new Stack<Character>();
Stack<Character> solutionStack = new Stack<Character>();
String solution = "";
for(char c : s.toCharArray())
{
if(Character.isLetter(c)||Character.isDigit(c))
{
solutionStack.push(c);
}
else if(c == '(')
{
opStack.push(c);
solutionStack.push(')');
}
else if(c == ')')
{
while(opStack.peek() != '(')
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
opStack.pop();
}
else if (!Character.isSpaceChar(c))
{
if(opStack.isEmpty())
{
opStack.push(c);
}
else if(opStack.peek()!='(' &&(OPERATORS.indexOf(c) < OPERATORS.indexOf(opStack.peek())))
{
opStack.push(c);
}
else if(!opStack.isEmpty()&&(opStack.peek()!='('))
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
opStack.push(c);
}
else
{
opStack.push(c);
}
}
}
while(opStack.size() != 0)
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
while(!solutionStack.isEmpty())
{
solution+=solutionStack.pop();
}
System.out.println("Final Answer!"+solution);
This 正确输出左括号,但只有一种右括号。有人知道我应该在哪里添加它们吗?我发誓我错过了到达目的地的最后一个逻辑步骤......
I'm working on what is essentially the shunting yard algorithm, but moving infix to prefix instead of RPN
I am trying to preserve parenthesis, and I'm having a devil of a time of it. Currenntly my code is
String s = inFixList.get(i);
Stack<Character> opStack = new Stack<Character>();
Stack<Character> solutionStack = new Stack<Character>();
String solution = "";
for(char c : s.toCharArray())
{
if(Character.isLetter(c)||Character.isDigit(c))
{
solutionStack.push(c);
}
else if(c == '(')
{
opStack.push(c);
solutionStack.push(')');
}
else if(c == ')')
{
while(opStack.peek() != '(')
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
opStack.pop();
}
else if (!Character.isSpaceChar(c))
{
if(opStack.isEmpty())
{
opStack.push(c);
}
else if(opStack.peek()!='(' &&(OPERATORS.indexOf(c) < OPERATORS.indexOf(opStack.peek())))
{
opStack.push(c);
}
else if(!opStack.isEmpty()&&(opStack.peek()!='('))
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
opStack.push(c);
}
else
{
opStack.push(c);
}
}
}
while(opStack.size() != 0)
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
while(!solutionStack.isEmpty())
{
solution+=solutionStack.pop();
}
System.out.println("Final Answer!"+solution);
This outputs the opening parenthesis correctly, but only one kind of closing parenthesis. Does anybody have any idea where I should be adding them? I swear I'm missing that last logical step to get where it goes...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这是否是问题所在,但我注意到在您编写的代码中
您真的想在此处添加右括号吗?推入左括号似乎更合理,尽管我可能是错的。
I'm not sure if this is the problem, but I noticed in your code that you wrote
Do you really want to push a close parenthesis here? Pushing an open parenthesis seems a lot more reasonable, though I could be wrong.