balancedParens

Written on August 8, 2019

문제

Write a function that takes a string of text and returns true if the parentheses are balanced and false otherwise.

Example:

  • balancedParens(‘(‘); // false
  • balancedParens(‘()’); // true
  • balancedParens(‘)(‘); // false
  • balancedParens(‘(())’); // true


Step 2: make your solution work for all types of brackets

Example:

  • balancedParens(‘{}’); // true
  • balancedParens(‘[({})]’); // true
  • balancedParens(‘[(]{)}’); // false


Step 3: ignore non-bracket characters

  • balancedParens(‘ var wow = { yo: thisIsAwesome() }’); // true
  • balancedParens(‘ var hubble = function() { telescopes.awesome();’); // false

풀이

var balancedParens = function(input) {
  let parens = ["(", ")", "[", "]", "{", "}"];
  let parensOnly = input
    .split("")
    .filter(char => parens.includes(char))
    .join("");
  let isBalanced = true;
  const parensFiler = str => {
    if (str.includes("()")) {
      let filteredStr = str.split("()").join("");
      parensFiler(filteredStr);
    } else if (str.includes("[]")) {
      let filteredStr = str.split("[]").join("");
      parensFiler(filteredStr);
    } else if (str.includes("{}")) {
      let filteredStr = str.split("{}").join("");
      parensFiler(filteredStr);
    } else if (str.length > 0) {
      isBalanced = false;
      return;
    } else {
      return;
    }
  };
  parensFiler(parensOnly);
  return isBalanced;
};

👩🏻‍💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻‍♀️

in the process of becoming the best version of myself