20. Valid Parentheses(stack)

来源:互联网 发布:热传导分析软件 编辑:程序博客网 时间:2024/05/22 04:24

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.

answer

class Solution {public:    bool isValid(string s) {        stack<char> pStack;        int i = 0;        // if(s.size() == 1){        //     return false;        // }        while(s[i] != '\0'){            // if(pStack.empty() && (s[i]==')') || s[i]==']' || s[i]=='}'){            //     return false;            // }            if(s[i] == '(' || s[i] == '[' || s[i] == '{'){                pStack.push(s[i++]);            }            else if(!pStack.empty() && ((s[i] == ')' && pStack.top() == '(') || (s[i] == ']' && pStack.top() == '[') || (s[i] == '}' && pStack.top() == '{'))){                pStack.pop();                i++;            }            else{                return false;            }        }        if(!pStack.empty()){            return false;        }        return true;    }};

time:0ms

0 0
原创粉丝点击