[leedcode oj 20]Valid Parentheses

来源:互联网 发布:页面加载慢如何优化 编辑:程序博客网 时间:2024/06/05 09:34

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.


大清早起来做题我也是醉了。。。叔叔快来表扬我。。。(卖萌完毕。。。

由于形式语言刚学完。。。然后第一个想法就是压栈然后配对弹栈,最后看见栈底了,那就是valid


class Solution {public:    bool isValid(string s) {        stack<char> charStack;//这货以前没用过,一个栈的类型        int i = 0;        while(i != s.length())        {            char c = s[i];            if(c == '(' || c == '[' || c == '{')            {                charStack.push(c);//好高级,自己就有push pop操作            }            else            {                if(charStack.size() == 0)//结构体里面还有大小。。。这是操作系统的节奏。。。                    return false;                char tmp = charStack.top();                switch(c)                {                    case ')':                        if(tmp == '(')                            charStack.pop();                        else                            return false;                        break;                    case ']':                        if(tmp == '[')                            charStack.pop();                        else                            return false;                        break;                    case '}':                        if(tmp == '{')                            charStack.pop();                        else                            return false;                        break;                }            }            i++;        }        if(charStack.size() == 0)            return true;        else            return false;    }};

一遍过也是很爽的一件事。。。原来C++有这么多结构体。。。都没用过。。。摔。。。


0 0