20 Valid Parentheses

来源:互联网 发布:dsc分析软件下载 编辑:程序博客网 时间:2024/06/05 17:17

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.

记得玩过一个手机游戏,叫做《黑客》,也有这个匹配括号的题。

class Solution {public:    bool isValid(string s) {        if (s.length() % 2)        {            return false;        }            stack<char> brackets;        int i = 0;        while (i < s.length())        {            if (brackets.empty())            {                brackets.push(s[i]);            }            else             {                if ((brackets.top() == '(' && s[i] == ')') ||                     brackets.top() == '[' && s[i] == ']' ||                     brackets.top() == '{' && s[i] == '}' )                {                    brackets.pop();                }                else                {                    brackets.push(s[i]);                }            }            ++i;        }        return brackets.size() == 0;    }};
0 0
原创粉丝点击