ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของ expressions ทางคณิตศาสตร์ 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