6
\$\begingroup\$

The task is taken from leetcode

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Note that an empty string is also considered valid.

Example 1:

Input: "()"

Output: true

Example 2:

Input: "()[]{}"

Output: true

Example 3:

Input: "(]"

Output: false

Example 4:

Input: "([)]"

Output: false

Example 5:

Input: "{[]}"

Output: true

My functional solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = s => {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  return [...s].every(x => par[x] 
                      ? rep.push(par[x])
                      : rep.pop() === x) && !rep.length;
};

My imperative soltion

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid2 = s => {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  for (let i = 0; i < s.length; i++) {
    if (par[s[i]]) {
      rep.push(par[s[i]]);
    } else {
      if (rep.pop() !== s[i]) {
        return false;
      }
    }
  }
  return rep.length === 0;
};
\$\endgroup\$
1
\$\begingroup\$

The code looks quite succinct and sufficient. The only suggestions I would offer are minor tweaks:

  • for the imperative solution, a for...of loop could be used to eliminate the need to do bookkeeping on the counter variable and use it to index into the string to get each character:

    for(const c of s) {
      if (par[c]) {
        rep.push(par[c]);
      } else {
      if (rep.pop() !== c) {
        return false;
      }
    }
    
  • for the functional solution, the callback function could be declared on a previous line, and then the return line can be reduced to a single line:

    const pushOrPopMatch = x => par[x] ? rep.push(par[x]) : rep.pop() === x
    return [...s].every(pushOrPopMatch) && !rep.length;
    

    That line defining pushOrPopMatch() is 73 characters long, which some might argue is too long for a line, given it would be inside a function and indented at least two spaces, so it may not be ideal

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.