괄호 변환

2020.07.30

const mapHelper = (char) => {
  if (char == "(") {
    return ")";
  }
  return "(";
};

const solution = (p) => {
  if (!p) {
    return "";
  }

  const stack = [];
  let balance = 0;

  let index;
  const limit = p.length;
  for (index = 0; index < limit; index++) {
    const current = p[index];
    if (current == "(") {
      balance++;
      stack.push(0);
    } else {
      balance--;
      stack.pop();
    }
    if (balance == 0) {
      break;
    }
  }

  const arrOfP = p.split("");
  const arrOfU = arrOfP.splice(0, index + 1);

  const u = arrOfU.join("");
  const v = arrOfP.join("");
  if (stack.length == 0) {
    return u + solution(v);
  }
  arrOfU.shift();
  arrOfU.pop();
  return "(" + solution(v) + ")" + arrOfU.map(mapHelper).join("");
};
  • 자꾸 배열과 문자열을 왔다갔다하니 실행 시간이 길어지는 문제가 있었다.
const mapHelper = (char) => (char == "(" ? ")" : "(");

const solution = (p) => {
  if (!p) {
    return "";
  }

  const stack = [];
  let balance = 0;

  let index;
  const limit = p.length;
  for (index = 0; index < limit; index++) {
    const current = p[index];
    if (current == "(") {
      balance++;
      stack.push(0);
    } else {
      balance--;
      stack.pop();
    }
    if (balance == 0) {
      break;
    }
  }

  const u = p.slice(0, index + 1);
  const v = p.slice(index + 1);

  if (stack.length == 0) {
    return u + solution(v);
  }

  return (
    "(" +
    solution(v) +
    ")" +
    u
      .split("")
      .slice(1, u.length - 1)
      .map(mapHelper)
      .join("")
  );
};

0개의 댓글