Compass Interview Question: Checking if a string contains... | Glassdoor

Interview Question

Software Engineer Interview

Checking if a string contains a valid sequence of opening

  and closing parentheses
Answer

Interview Answer

1 Answer

0

var isValid = function(s) {
  let chars = {
    "(": ")",
    "{": "}",
    "[": "]"
  };
  let pickStack = s.split("");
  let pushStack = [];
  while (pickStack.length > 0) {
    let char = pickStack.pop();
    if (char == "(" || char == "{" || char == "[") {
      if (pushStack.length == 0) {
        return false;
      }
      let pushedChar = pushStack.pop();
      if (pushedChar != chars[char]) {
        return false;
      }
    } else {
      pushStack.push(char);
    }
  }
  if (pushStack.length > 0) {
    return false;
  }
  return true;
};

teoman on Apr 3, 2019

Add Answers or Comments

To comment on this, Sign In or Sign Up.