쇠막대기

2020.07.29

const isLaser = (current, next) => current == "(" && next == ")";

const solution = (arrangement) => {
  let count = 0;
  const stack = [];
  const arrOfInput = arrangement.split("");
  const limit = arrangement.length;
  for (let i = 0; i < limit; i++) {
    const current = arrOfInput[i];
    if (isLaser(current, arrOfInput[i + 1])) {
      count += stack.length;
      i++;
      continue;
    }
    if (current == "(") {
      stack.push("(");
      continue;
    }
    if (current == ")") {
      stack.pop();
      count++;
      continue;
    }
  }
  return count;
};
  • 사실 예전에 풀어봤을 때 다른 사람의 풀이 중 인상 깊었던 부분이 있어서 그걸 떠올리면서 풀었다.
const solution = (arrangement) => {
  let count = 0;
  const stack = [];
  const arrOfInput = arrangement.split("()").join("!");
  const limit = arrangement.length;
  for (let i = 0; i < limit; i++) {
    const current = arrOfInput[i];
    if (current == "!") {
      count += stack.length;
      continue;
    }
    if (current == "(") {
      stack.push("(");
      continue;
    }
    if (current == ")") {
      stack.pop();
      count++;
      continue;
    }
  }
  return count;
};
  • 정규표현식이나 split/join메소드를 활용하여 레이저 부분을 치환하는 것이 보기에 더 직관적인데 실행 시간이 다소 길어지는 것은 감안해야 한다.

0개의 댓글