Leetcode(19)

来源:互联网 发布:网络社交的利弊二辩 编辑:程序博客网 时间:2024/05/17 05:14

https://leetcode.com/problems/valid-parentheses/#/description

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution:

经典的匹配题,用stack来解决。

bool ValidParentheses::isValid(std::string s) {    std::stack<char> leftParentheses;    for (char c : s) {        if (c == '(' || c == '[' || c == '{') {            leftParentheses.push(c);        } else if (c == ')' || c == ']' || c == '}') {            char leftParenthese = ' ';            switch (c) {                case ')':                    leftParenthese = '(';                    break;                case ']':                    leftParenthese = '[';                    break;                case '}':                    leftParenthese = '{';                    break;            }            if(leftParentheses.empty() || leftParentheses.top() != leftParenthese) {                return false;            }            leftParentheses.pop();        }    }    return leftParentheses.empty();}

原创粉丝点击