입력 (자바 스크립트) "3-2 + (8-3)"입니다 입환 마당 알고리즘 불필요한 괄호
내가 역 폴란드 표기법이 표현을 번역 할. 그러나 알고리즘에 따르면 "결과를 평가하지 않는"3 2 8 3 - + - "을 얻을 수 있습니다. 나는 오, 음 ... 내가 아래에있는 내 기능을 가지고, 괄호 여기 불필요 알고 있지만 : 함수의 논리에 오류가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가되어야합니다. f 6. –
당신의 regex는 훨씬 간단 할 수 있습니다 [abc]는 a, b 또는 c 중 하나를 의미합니다. 대괄호 [a] 안에 하나의 항목 만있는 경우 단일 문자로 바꿀 수 있습니다. | | 대신에 사용할 수도 있습니다. 대안으로 a | b는 [ab]로 쓰여질 수있다. 특히/[+] | [-] | [*] | [\ /] /는/[+ = * \ /]/및/[(]/단순히 /로 대체 할 수 있습니다/(/. –