ввода (в JavaScript) является "3-2 + (8-3)"Шунтирование Yard Алгоритм ненужными скобки
Я хочу, чтобы перевести это выражение Reverse Polish Notation. Однако, согласно алгоритму, я могу получить «3 2 8 3 - + -», который не оценивает результат 12 ..... Любая работа вокруг метода для этого? Я знаю, что круглые скобки не нужны здесь, но, да ладно ... У меня есть функция ниже:
function ShuntingYard(str){
str=str.replace(/\)\(/g, ")*(");
var arr=str.split("");
var sYqueue=[];
var sYstack=[];
while (arr.length>0){
var token=arr.shift();
if (/\d+/.test(token)){
// if it's a number, push to the queue
sYqueue.push(token);
} // end if
else if (/[+]|[-]|[*]|[\/]/.test(token)){
// if it's an operator
if (sYstack.length==0){
// if an empty operator stack
sYstack.push(token);
}
else{
while ((/[*]|[\/]/.test(sYstack[sYstack.length-1])) &&
(/[+]|[-]/.test(token))){
// if the TOS has operator with higher precedence
// then need to pop off the stack
// and add to queue
console.log(sYstack);
sYqueue.push(sYstack.pop());
}
sYstack.push(token);
}
}
else if (/[(]/.test(token)){
// if it's left parenthesis
sYstack.push(token);
}
else if (/[)]/.test(token)){
// if it's right parenthesis
while (!(/[(]/.test(sYstack[sYstack.length-1]))){
// while there's no left parenthesis on top of the stack
// then need to pop the operators onto the queue
sYqueue.push(sYstack.pop());
} // end while
if (sYstack.length==0)
{ // unbalanced parenthesis!!
console.log("error, unbalanced parenthesis");
}
else
{
sYstack.pop(); // pop off the left parenthesis
}
}
else{
// other cases
}
} // end while
// now while the stack is not empty, pop every operators to queue
while (sYstack.length>0){
sYqueue.push(sYstack.pop());
}
return sYqueue;
} // end function ShuntingYard
почему результат должен быть 12 вместо o f 6. –
Ваши ретрансляции могут быть намного проще [abc] означает любой из a, b или c. Если в скобках [a] имеется только один элемент, вы можете заменить его одним символом. Вы также можете использовать их вместо | для альтернатив, поэтому a | b может быть записано как [ab]. В частности,/[+] | [-] | [*] | [\ /]/можно заменить на/[+ = * \ /]/и/[(]/заменить просто/(/. –