Task with braces, brackets and parenthesis

前端 未结 5 1279
予麋鹿
予麋鹿 2021-01-29 14:38

Task is to check if given string contains balanced sets of {}, [] and ().

For example, check(\"{[}]\") must return

5条回答
  •  臣服心动
    2021-01-29 14:43

    This task is not doable with a regex because they have no memory and cannot remember the depth of parenthesing.

    You should use a parser, probably a recursive descent parser, to do the task.

    The grammar would look like this (not tested):

    input: /* empty */
         | expr input
    
    expr: paren-expr
        | bracket-expr
        | curly-bracket-expr
    
    paren-expr: '(' input ')'
    
    bracket-expr: '[' input ']'
    
    curly-bracket-expr: '{' input '}'
    

    Example code:

    #include 
    #include 
    #include 
    
    
    class parenthesis_checker {
    
      template 
      It parse_open_close(It first, It last, char op, char cl) const {
        if(op != *first) return first;
    
        It r = parse_input(first+1, last);
        if(last == r) return first;
        if(cl != *r)  return first;
    
        return r+1;
      }
    
      template 
      It parse_expr(It first, It last) const {
        It r = parse_open_close(first, last, '(', ')');
        if(r != first) return r;
    
        r = parse_open_close(first, last, '[', ']');
        if(r != first) return r;
    
        r = parse_open_close(first, last, '{', '}');
        if(r != first) return r;
    
        return first;
      }
    
      template 
      It parse_input(It first, It last) const {
        while(first != last) {
          It r = parse_expr(first, last);
          if(r == first) return r;
          first = r;
        }
        return first;
      }
    
    public:
      template 
      bool operator()(It first, It last) const {
        return last==parse_input(first, last);
      }
    
      template 
      bool operator()(Cont value) const {
        return (*this)(value.begin(), value.end());
      }
    
      bool operator()(const char* str) const {
        return (*this)(std::string(str));
      }
    };
    
    
    int main() {
      parenthesis_checker check;
    
      std::cout << check("{[}]") << std::endl;
      std::cout << check("{[]()}") << std::endl;
    }
    

提交回复
热议问题