Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การลบวงเล็บออกจากนิพจน์คณิตศาสตร์ใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของนิพจน์คณิตศาสตร์ str เป็นอาร์กิวเมนต์เดียว

ภารกิจของฟังก์ชันคือลบวงเล็บออกจากนิพจน์ พร้อมทั้งรักษาการดำเนินการและตัวถูกดำเนินการไว้ในตำแหน่งเดิม

ตัวอย่างเช่น หากอินพุตคือ

อินพุต

const str = 'u-(v-w-(x+y))-z';

เอาต์พุต

const output = 'u-v+w+x+y-z';

ตัวอย่างโค้ด

const str = 'u-(v-w-(x+y))-z';
const removeParentheses = (str = '') => {
let stack = [];
let lastSign = '+';
for (let char of str) {
if (char === '(' || char === ')') {
lastSign = stack[stack.length - 1] || '+';
} else if (char === '+') {
if (stack[stack.length - 1] !== '-' && stack[stack.length - 1] !== '+') {
stack.push(lastSign);
}
} else if (char === '-') {
if (lastSign === '-') {
if (stack[stack.length - 1] === '-') stack.pop();
stack.push('+');
} else {
if (stack[stack.length - 1] === '+') stack.pop();
stack.push('-');
}
} else {
stack.push(char);
}
}
return stack.join('').replace(/^\+/, '');
};
console.log(removeParentheses(str));

ผลลัพธ์

u-v+w+x+y-z