Task with braces, brackets and parenthesis

前端 未结 5 1320
予麋鹿
予麋鹿 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:53

    Checking for nested braces seems like a natural case for std::stack. Push braces onto the stack as you iterate over the input and test for correct matches when you see a closing brace.

    bool check(const std::string &expression) // balanced and nested?
    {
        std::stack stack;
    
        for (auto ch : expression) {
            switch (ch) {
            case '(': // open parenthesis
            case '<': // open angle
            case '[': // open bracket
            case '{': // open brace
                stack.push(ch);
                break;
            case ')': // close parenthesis
                if (stack.empty() || stack.top() != '(') return false;
                stack.pop();
                break;
            case '>': // close angle
                if (stack.empty() || stack.top() != '<') return false;
                stack.pop();
                break;
            case ']': // close bracket
                if (stack.empty() || stack.top() != '[') return false;
                stack.pop();
                break;
            case '}': // close brace
                if (stack.empty() || stack.top() != '{') return false;
                stack.pop();
                break;
            }
        }
        return stack.empty(); // no unmatched braces left?
    }
    

提交回复
热议问题