我正在研究什么本质上是分流码算法,但移动中缀前缀而不是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);
正确输出左括号,但只输出一种右括号。有人知道我应该把它们加在哪里吗?
我不确定这是否是问题,但我注意到在你的代码中,你写
else if(c == '(')
{
opStack.push(c);
solutionStack.push(')');
}
你真的想在这里加一个右括号吗?按开括号似乎更合理,尽管我可能是错的。