找出括号中的所有内容,有什么更好的写法吗?-灵析社区

素素数数

const str = 'a+b*(d-e)*c+(((b+a)+f)+g)' let current = 0, res = []; function test() { let letter = str[current]; if (letter === '(') { if(str[++current] === "("){ letter = str[current] } else { letter = ''; } while (current

阅读量:257

点赞量:14

问AI
function extractSubExpressions(str: string): string[] { const stack: number[] = []; const subExpressions: string[] = []; for (let i = 0; i < str.length; i++) { if (str[i] === "(") { stack.push(i); } else if (str[i] === ")") { if (stack.length === 0) { throw new Error("Invalid expression: Incorrect bracket placement"); } const startIndex = stack.pop()!; const subExpression = str.substring(startIndex, i + 1); const replaceStr = subExpression.substr(1,subExpression.length-2) subExpressions.push(replaceStr); } } if (stack.length !== 0) { throw new Error("Invalid expression: Unclosed brackets"); } return subExpressions; } const str = 'a+b*(d-e)*c+(((b+a)+f)+g)'; const result = extractSubExpressions(str); console.log(result); // ['d-e', 'b+a', '(b+a)+f', '((b+a)+f)+g']