20. Valid Parentheses #Stack (Easy)

Problem:###

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:###

Very classic stack problem.
If meet any left parentheses, push it into stack.
If meet any right parentheses, check whether the top of the stack is the proper left parentheses. If valid, pop it. If not valid, return false.
Finally check whether the stack is empty. If it's not empty, then it's also invalid.

class Solution {
public:
    bool isValid(string s) {
        bool result = true;
        if(s.size() == 0) return true;
        stack<char> p;
        for(int i = 0;i < s.size();i++)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{')
                p.push(s[i]);
            else
            {
                if (p.empty()) 
                    return false;
                if (s[i] == ')' && p.top() == '(') p.pop();
                else if (s[i] == ']' && p.top() == '[') p.pop();
                else if (s[i] == '}' && p.top() == '{') p.pop();
                else
                    return false;
            }
        }
        if (!p.empty()) //important!!!!!!!
            return false;
        return result;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,132评论 0 23
  • 觉得声音比以前好听点啦 优点: 1.快准,有点找到感觉 2.互动感变强 3.讲的比较细 缺点: 1.仪式感太强,亲...
    cindy蕾蕾阅读 181评论 0 0
  • 今天和先生、Peter、业务员聊了下关于线上的事情,启发很多,之前一心追求的东西现在看来还不是时机,只有脚踏实地一...
    王德彪阅读 173评论 0 0
  • 存储属性计算属性属性观察器类型属性 存储属性 存储常量或变量作为实例的一部分,用于类和结构体。 栗子 等下!😲 先...
    HunterDude阅读 529评论 0 4
  • 文/谌基平 类似像我这种带点某个领域的“专家”性质的人,经常在微信上遇到这样的场景 请问新媒体营销怎么做? 请问小...
    谌基平阅读 804评论 0 0