DEV Community

Discussion on: [C++ CODE] Valid Parenthesis

Collapse
 
picolloo profile image
Lucas

I have done like this:

bool validateBrackets(const std::string& data) {

  std::stack<char> brackets;  

  for (const auto& d : data) {
    if (d == '[' || d == '(' || d == '{') {
      brackets.push(d);
    }      
    else if (d == ']') {
     if (brackets.top() == '[')
       brackets.pop(); 
      else 
        return false;
    }
    else if (d == ')') {
     if (brackets.top() == '(')
       brackets.pop();
      else 
        return false;
    }
    else if(d == '}') {
     if (brackets.top() == '{')
       brackets.pop();
      else 
        return false;
    }
  }

  return true;
}

Collapse
 
thetealpickle profile image
✨ thetealpickle πŸ“±

yasss πŸ‘πŸ‘ I like the direct comparison for the bracket pairings. More efficient than a map 😬😁