用字符串中的外括号拆分字符串

Split string with the outer bracket in string

我想拆分一个字符串

(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)

(即拆分外括号外由运算符分隔的字符串)

像这样的数组

array = [
  "(B+(([A/C]+D)*E))",
  "([(([A/F]+G)/H])*I)",
  "([A/J]+K*L)"
];

我尝试使用 split() 但失败了。

谢谢。

我认为栈的概念会解决这个问题。

function solve(str) {
  const operators = ['+', '-', '/', '*'];

  const result = [];
  let stack = 0;
  let current = '';

  for (let i = 0; i < str.length; i++) {
    current += str[i];

    if (str[i] === '(') stack++;
    else if (str[i] === ')') stack--;

    if (stack === 0) {
      if (!operators.includes(current)) {
        result.push(current);
      }

      current = '';
    }
  }

  return result;
}

const array = solve('(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)');
console.log(array); // [ '(B+(([A/C]+D)*E))', '([(([A/F]+G)/H])*I)', '([A/J]+K*L)' ]

const str = '(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)';
const splitByBrackets = (str) => {
  const operators = ['+', '-', '/', '*'];
  const stack = [];
  const result = [];
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char === '(') {
      stack.push(char);
    }
    if (char === ')') {
      stack.pop();
    }
    if (operators.includes(char) && stack.length === 0) {
      result.push(str.slice(0, i));
      str = str.slice(i + 1);
      i = -1;
    }
  }
  result.push(str);
  return result;
};
console.log(splitByBrackets(str));

另一种解析字符串的方法是用通用分隔符替换所有字符条目,并用此分隔符分隔字符串;

const str = '(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)';
const operators = ['+', '-', '/', '*'];
const sep= '|||';

const result = operators
  .reduce((acc, sign) => acc.replaceAll(`)${sign}(`, sep), str)
  .split(sep);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}